我有一个pandas数据集,该数据集包含一列为其分配到的组。但是我想自定义节点的颜色。例如,对于组0,节点为红色,对于组1,节点为蓝色。这是我根据研究尝试过的方法,但是由于某种原因,它并没有真正按照分组进行(基于分组的颜色只有2种),并且我无法编辑颜色。
这是我保存在sample.csv文件中的数据集
ID|Parent|Group|
1 | 5 | 0 |
2 | 5 | 0 |
3 | 4 | 1 |
4 | 5 | 1 |
5 | 3 | 0 |
sample= pd.read_csv('sample.csv', encoding='cp1252')
G=nx.from_pandas_edgelist(sample, 'ID', 'Parent', create_using=nx.DiGraph())
carac=sample.set_index('ID')
carac=sample.reindex(G.nodes())
carac['Group']=pd.Categorical(carac['Group'])
carac['Group'].cat.codes
plt.figure(2,figsize=(5,5))
nx.draw(G, node_color=carac['Group'].cat.codes, cmap=plt.cm.Set1, node_size=150)
# Build your graph
G=nx.from_pandas_edgelist(sample, 'ID', 'Parent', ['Group'], create_using=nx.DiGraph())
G.nodes()
colors = []
for node in G:
if node in (sample["Group"] == 0):
colors.append("red")
elif node in (sample["Group"]== 1):
colors.append("blue")
nx.draw(G, with_labels=False, node_size=150, node_color=colors)
答案 0 :(得分:1)
node_color不是用于节点组,而是用于每个节点本身。您应将图形中每个节点的颜色添加到colors
:
node_color (color string, or array of floats, (default=’#1f78b4’)) – Node color. Can be a single color format string, or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details.
G = nx.gnm_random_graph(20, 50, directed=True)
# Not for groups, but for each node
colors = ['red' if n > 10 else 'blue' for n in G.nodes]
nx.draw(G, with_labels=False, node_size=150, node_color=colors)
还请注意您的colors
数组长度等于G.nodes
的长度!如果它们不同,则node_color
将被忽略!
G = nx.gnm_random_graph(20, 50, directed=True)
# Because of .pop(), the length of colors is different
colors = ['red' if n > 10 else 'blue' for n in G.nodes].pop()
nx.draw(G, with_labels=False, node_size=150, node_color=colors)