python 基于度中心度度量的networkx图的颜色和大小变化

uemypmqf  于 2023-03-11  发布在  Python
关注(0)|答案(2)|浏览(146)

我尝试做的是使用NetworkX库来计算度中心性,然后基于这个度量来改变不同节点的颜色和大小。
预期的结果是节点根据其度中心性显示为不同的颜色和大小,但目前,它们只显示默认颜色,因为我不知道应该怎么做。
我在这个项目中使用的csv文件可以在这里找到。https://www.mediafire.com/file/q0kziy9h251fcjf/nutrients.csv/file
该文件当前没有错误消息,只是颜色大小没有更改。
我最近尝试过做一些列表理解来解决这个问题,但我还不确定如何做,或者如何设置颜色Map(什么颜色并不重要)
这是我目前正在使用的代码。

import networkx as nx
import matplotlib.pyplot as plt

Data = open('nutrients.csv', "r")
next(Data, None)
Graph_type = nx.Graph()

G = nx.parse_edgelist(Data, delimiter=',', create_using=Graph_type,
                      nodetype=str, data=(('weight', float),))

deg_centrality = nx.degree_centrality(G)
print(deg_centrality)

pos = nx.spring_layout(G)
nx.draw(G, pos)
plt.show()

数据

A,carrots
A,eggs
A,"fatty fish"
A,"green leafy vegs"
A,liver
A,milk
A,tomatoes
B12,milk
B6,asparagus
B6,beans
B6,"fatty fish"
B6,kidneys
B6,liver
B6,potatoes
C,carrots
C,pumpkins
C,tomatoes
Ca,broccoli
Ca,cheese
Cu,liver
Cu,nuts
Cu,"whole grains"
D,"fatty fish"
D,milk
D,mushrooms
E,nuts
E,seeds
Mn,"green leafy vegs"
Mn,legumes
Mn,nuts
Mn,seeds
Mn,wheat
Mn,"whole grains"
Se,kidneys
Zn,beans
Zn,kidneys
Zn,potatoes
beans,Cu
beef,B12
beef,B6
beef,Zn
beef,riboflavin
broccoli,C
eggs,B12
eggs,riboflavin
"fatty fish",B12
"fatty fish",niacin
folates,asparagus
folates,liver
folates,spinach
"green leafy vegs",C
"green leafy vegs",Ca
"green leafy vegs",E
"green leafy vegs",riboflavin
kidneys,Cu
legumes,riboflavin
liver,Se
liver,Zn
milk,Ca
milk,riboflavin
niacin,beef
niacin,nuts
niacin,seeds
niacin,"whole grains"
nuts,Zn
potatoes,Cu
poultry,B12
poultry,B6
poultry,Zn
shellfish,Cu
shellfish,Se
thiamin,"whole grains"
tomatoes,tomatoes
"veg oils",E
yogurt,Ca
6pp0gazn

6pp0gazn1#

像这样的怎么样?

import numpy as np
import matplotlib.colors as mcolors
import matplotlib.cm as cm

cent = np.fromiter(deg_centrality.values(), float)
sizes = cent / np.max(cent) * 200
normalize = mcolors.Normalize(vmin=cent.min(), vmax=cent.max())
colormap = cm.viridis

scalarmappaple = cm.ScalarMappable(norm=normalize, cmap=colormap)
scalarmappaple.set_array(cent)

plt.colorbar(scalarmappaple)
nx.draw(G, pos, node_size=sizes, node_color=sizes, cmap=colormap)
plt.show()

我引入了一个任意的缩放因子,您可以调整它来创建其他大小。Numpy用于方便缩放,但您可以对vanilla Python执行相同的操作。
颜色Map表可以更改为您喜欢的任何颜色:https://matplotlib.org/stable/tutorials/colors/colormaps.html
编辑:我设法通过修改this answer创建了一个颜色渐变图例。

e4eetjau

e4eetjau2#

这是一个简单的代码,带有networkx的绘图函数:

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# create graph from data
with open("nutrients.csv", "r") as f:
    G = nx.parse_edgelist(f.readlines(), delimiter=",")

# centrality
deg_centrality = nx.degree_centrality(G)
centrality = np.fromiter(deg_centrality.values(), float)
# plot
pos = nx.kamada_kawai_layout(G)
nx.draw(G, pos, node_color=centrality, node_size=centrality*2e3)
nx.draw_networkx_labels(G, pos)
plt.show()

输出:

我强烈推荐使用plotlysee exemple)来进行交互。对于这种图形,我发现它真的很有用。

相关问题