pandas Pyvis和Networkx:如何根据源或目标使节点颜色不同

46qrfjad  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(91)

我已经把SO的几个答案串在一起,走到这里,但无法让节点显示不同的颜色。我的代码试图让Team节点显示为Red,而State节点显示为Black。但最终我希望在源文件中通过Type属性定义节点颜色(nfl=red,nba=black,mlb=绿色)。感谢任何帮助。
源文件csv:

team,state,Weight,type
Knicks,New York,9,nba
Warriors,California,9,nba
Giants,California,3,mlb
49ers,California,6,nfl
Cowboys,Texas,1,nfl
Giants,New York,2,nfl

字符串
代码:

import networkx as nx
import pandas as pd
from pyvis.network import Network

df = pd.read_csv('./data_files/sample.csv')

G = nx.from_pandas_edgelist(df,
                            source='team',
                            target='state',
                            edge_attr='Weight')

colors = []

for node in G:
    if node in df["team"].values:
        colors.append("red")
    else: 
        colors.append("black")

print(colors)

nx.draw(G, node_color=colors, with_labels=True)

net = Network(notebook=True, filter_menu=True, cdn_resources='remote')

net.from_nx(G)

net.show("./output/teams.html")

xjreopfe

xjreopfe1#

如果你需要根据type有条件地为其中一个节点着色,你可以创建一个map

default = "blue"

colors = dict(nfl="red", nba="black", mlb="green")

dmap = df.set_index("team")["type"].map(colors).to_dict()

nx.draw(G, node_color=[dmap.get(n, default) for n in G.nodes], with_labels=True)

字符串
注意:如果节点是 * 唯一的 *,你可以把两列Map在一起,这样:

dmap = (pd.lreshape(df, {"nodes": ["team", "state"]})
     .set_index("nodes")["type"].map(colors).to_dict())


如果您需要在保存html之前将颜色设置为属性,您可以使用:用途:

nx.set_node_attributes(G, dmap, "color") # << add this line

net.from_nx(G)

net.write_html("./output/teams.html")


Preview(of teams.html):


的数据

vnzz0bqm

vnzz0bqm2#

下面是一个使用gravis创建您请求的图形可视化的简短解决方案。源节点颜色由type列确定,边缘宽度来自DataFrame中的Weight列。
免责声明:我是gravis的作者,并提供了这个答案,因为像你这样的用例是构建这个包的动机的一部分,因此用它来生成合适的解决方案是很简单的。

import gravis as gv
import networkx as nx
import pandas as pd

df = pd.read_csv('./data_files/sample.csv')
graph = nx.from_pandas_edgelist(df, source='team', target='state', edge_attr=('Weight', 'type'))
mapping = dict(nfl='red', nba='black', mlb='green')
for (source, target), attr in graph.edges.items():
    graph.nodes[source]['color'] = mapping[attr['type']]
    graph.edges[(source, target)]['size'] = attr['Weight'] / 2

fig = gv.d3(graph)
fig.display()  # opens a web browser with the visualization

字符串
除了fig.display(),你还可以使用fig.export_html(filename)来创建一个独立的HTML文件,或者使用fig.to_html()来获取HTML文本,你可以在Web应用程序中提供这些文本。如果你喜欢使用fig.display(),你还可以将可视化嵌入到输出单元格中:

相关问题