问题
Imagine you have a network of 10 nodes and the nodes value is values = [i for i in range(len(10))]
Now I want to color this network however, I only want a color map of the nodes that have a value less than 5. How do I do this?
Thank you in advance.
回答1:
For that, you can simply not include (filte out) those nodes you want to avoid when plotting in nx.draw
. If you do want to include them, though just without a colormap (perhaps a constant color), just use a constant color rather than removing those nodes. Here's an example using a random graph:
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)
To include all nodes, but have those <5
without any colormap:
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()
To directly remove them:
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})
来源:https://stackoverflow.com/questions/62863070/how-to-set-a-maximum-value-in-a-color-map-of-a-network-python