【问题标题】:Python Networkx with_pandas_edgelist: edges not taking proper color, while specifying node positionsPython Networkx with_pandas_edgelist:边缘没有采用正确的颜色,同时指定节点位置
【发布时间】:2020-05-30 17:49:57
【问题描述】:

我对 Python 很陌生,并开始学习 networkx 来绘制道路网络图。我必须指定节点位置。边缘颜色应取决于边缘的权重。我尝试使用 pandas 数据框来生成边缘。未指定位置时,边缘颜色可以正常工作。附上代码。

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)

但是,颜色不遵循容量值。我将分享一个例子。 这是它不必要地改变颜色的情况

另一个例子 - 这里的颜色应该改变,但它没有

The excel files are here for reference

另外,如果您能建议如何为此添加颜色条,那就太好了。

【问题讨论】:

    标签: python pandas networkx


    【解决方案1】:
    import 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);
    

    【讨论】:

    • 这里的“容量”会是“重量”吗?
    • 是的,抱歉,没有更新所有事件。查看修改后的版本。
    • 好的。但是,现在我没有得到节点标签。我之前也遇到过同样的问题,同时通过单独的命令绘制节点和边。
    • 好吧,你也可以单独绘制标签:查看最新编辑
    • 谢谢,看起来很棒,似乎工作正常。将在主代码上尝试。
    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多