Python Networkx with_pandas_edgelist: edges not taking proper color, while specifying node positions

蹲街弑〆低调 提交于 2020-06-01 05:10:07

问题


I am pretty new to Python and started learning networkx to plot a graph for a road network. I have to specify, the node positions. The edge color should be dependent on the weights of the edges. I tried using pandas dataframe to generate edges. The edge colors work fine when position is not specified. The code is attached.

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

# Necessary file-paths
l1 = 'file1.xlsx'
l2 = "file2.xlsx"

n1 = pd.read_excel(l1)
n1.head(10)

n2 = pd.read_excel(l2)
n2.head(2)

# Building graph
G = nx.from_pandas_edgelist(n1, 'Start Node', 'End Node', create_using=nx.Graph())

# Defining positions
pos = {}
for n in G.nodes():
    i = n2[n2["Nodes"] == n].index[0]
    pos[n] = (n2.loc[i, "x"], n2.loc[i, "y"])

# Plot the Graph
nx.draw(G, pos, with_labels=True, node_color='pink', node_size=30, alpha=0.8, font_size=2,
        edge_color=n1['Capacity'], width=1.0, figsize = (18,18), style="solid", edge_cmap=plt.cm.jet)

# Save the Figure
plt.savefig('Network.png', dpi=1000, facecolor='w', edgecolor='w',orientation='portrait',  
            papertype=None, format=None,transparent=False, bbox_inches=None, pad_inches=0.1)

However, the colors do not follow the capacity values. I will share an example. Here is the case where it unnecessarily changes color

Another example - Here the colors should change, but it does not

The excel files are here for reference

Also, if you can suggest how to add a color-bar to this, it would be great.


回答1:


import networkx aimport networkx as nx

# dummy data, Graph and positions
df = pd.DataFrame({
    'node1': np.random.choice([*'ABCDEFGHIJKL'], 10, replace=True),
    'node2': np.random.choice([*'ABCDEFGHIJKL'], 10, replace=True),
    'Capacity': np.random.rand(10)
})
G = nx.from_pandas_edgelist(df, source='node1', target='node2', edge_attr='Capacity')
pos = nx.spring_layout(G)

# extract the edge weight
edge_colors = [a['Capacity'] for u,v,a in G.edges(data=True)]

# draw nodes and edges separately. allows using colormap for edges.
nx.draw_networkx_nodes(G, pos=pos)
nx.draw_networkx_edges(G, pos=pos, edge_color=edge_colors, edge_cmap=plt.cm.viridis, edge_vmin=0, edge_vmax=np.max(edge_colors), width=5)
nx.draw_networkx_labels(G, pos=pos);



来源:https://stackoverflow.com/questions/62106487/python-networkx-with-pandas-edgelist-edges-not-taking-proper-color-while-speci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!