如何在网络的颜色图中设置最大值 (Python)
How to set a maximum value in a color map of a network (Python)
假设您有一个 10 个节点 的网络,节点值为 values = [i for i in range(len(10))]
现在我想给这个网络上色,但是,我只想要一个值小于 5 的节点的彩色图。我该怎么做?
提前致谢。
为此,您可以简单地不包括(过滤掉)在 nx.draw
中绘图时要避免的那些节点。如果您确实想要包含它们,尽管只是没有颜色图(可能是常量颜色),只需使用常量颜色而不是删除这些节点。这是一个使用随机图的示例:
import networkx as nx
import matplotlib as mpl
from matplotlib import pyplot as plt
G = nx.barabasi_albert_graph(10, 1)
# defines a colormap lookup table
nodes = sorted(list(G.nodes()))
low, *_, high = sorted(values)
norm = mpl.colors.Normalize(vmin=low, vmax=high, clip=True)
mapper = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.coolwarm)
要包含所有节点,但 <5
没有任何颜色图:
plt.subplots(figsize=(10,6))
nx.draw(G,
nodelist=values,
node_size=500,
node_color=[mapper.to_rgba(i) if i>5 else 'lightblue'
for i in values],
with_labels=True)
plt.show()
要直接删除它们:
plt.subplots(figsize=(10,6))
pos = nx.spring_layout(G)
nx.draw_networkx_edges(G, pos=pos)
nx.draw_networkx_nodes(G, pos=pos,
nodelist=[i for i in values if i>5],
node_color=[mapper.to_rgba(i)
for i in nodes if i>5])
nx.draw_networkx_labels(G, pos=pos,
labels={node:node for node in nodes if node>5})
假设您有一个 10 个节点 的网络,节点值为 values = [i for i in range(len(10))]
现在我想给这个网络上色,但是,我只想要一个值小于 5 的节点的彩色图。我该怎么做?
提前致谢。
为此,您可以简单地不包括(过滤掉)在 nx.draw
中绘图时要避免的那些节点。如果您确实想要包含它们,尽管只是没有颜色图(可能是常量颜色),只需使用常量颜色而不是删除这些节点。这是一个使用随机图的示例:
import networkx as nx
import matplotlib as mpl
from matplotlib import pyplot as plt
G = nx.barabasi_albert_graph(10, 1)
# defines a colormap lookup table
nodes = sorted(list(G.nodes()))
low, *_, high = sorted(values)
norm = mpl.colors.Normalize(vmin=low, vmax=high, clip=True)
mapper = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.coolwarm)
要包含所有节点,但 <5
没有任何颜色图:
plt.subplots(figsize=(10,6))
nx.draw(G,
nodelist=values,
node_size=500,
node_color=[mapper.to_rgba(i) if i>5 else 'lightblue'
for i in values],
with_labels=True)
plt.show()
要直接删除它们:
plt.subplots(figsize=(10,6))
pos = nx.spring_layout(G)
nx.draw_networkx_edges(G, pos=pos)
nx.draw_networkx_nodes(G, pos=pos,
nodelist=[i for i in values if i>5],
node_color=[mapper.to_rgba(i)
for i in nodes if i>5])
nx.draw_networkx_labels(G, pos=pos,
labels={node:node for node in nodes if node>5})