Reputation: 483
I'm drawing two types of figures, for which I want to align the colors:
Both figures rely on a dictionary with node_names as keys, and ints as values, and a matplotlib.colors.LinearSegmentedColormap
cmap. Like the following:
import matplotlib.pyplot as plt
Dict = {"Alice": 0, "Bob": 1, "Carol": 2}
cmap = plt.cm.Accent
This allows me to get a unique color for each name. For this example:
for key, value in Dict.iteritems():
print key, value, cmap(value)
gives me
Bob 1 (0.50482122313742539, 0.78532873251858881, 0.50718954287323292, 1.0)
Alice 0 (0.49803921580314636, 0.78823530673980713, 0.49803921580314636, 1.0)
Carol 2 (0.51160323047170453, 0.7824221582973705, 0.5163398699433196, 1.0)
Which can be used as follows:
plt.hlines(1, 1, 5, cmap(Dict["Alice"]))
plt.hlines(2, 1, 5, cmap(Dict["Bob"]))
plt.hlines(3, 1, 5, cmap(Dict["Carol"]))
These values, however, do not at all match the result I get when I draw the following network:
G = nx.Graph()
G.add_nodes_from(Dict.keys())
nx.draw_networkx(G, nodelist=Dict.keys(), node_color=range(3), \
cmap=plt.cm.Accent)
For the plot of the network I get 3 clearly distinct colors, but for the hlines they are virtually indistinguishable.
What am I missing about how nx.draw_networkx
uses node_color
and cmap
?
Upvotes: 4
Views: 2202
Reputation: 25289
You'll need to map your values into the [0,1] colormap range. Do this explicitly for your hline drawings - networkx's interface to maptlotlib will do it for you and you can specify the min and max. Note that for the call networkx.draw_networkx
the nodelist order and node_color order must be the same.
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib as mpl
Dict = {"Alice": 0, "Bob": 1, "Carol": 2}
cmap = plt.cm.Accent
norm = mpl.colors.Normalize(vmin=0, vmax=2)
m = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
for key, value in Dict.iteritems():
print key, value, m.to_rgba(value)
plt.hlines(1, 1, 5, m.to_rgba(Dict["Alice"]), linewidth=50)
plt.hlines(2, 1, 5, m.to_rgba(Dict["Bob"]), linewidth=50)
plt.hlines(3, 1, 5, m.to_rgba(Dict["Carol"]), linewidth=50)
G = nx.Graph()
G.add_nodes_from(Dict.keys())
nodelist,node_color = zip(*Dict.items())
nx.draw_networkx(G, nodelist=nodelist, node_size=1000, node_color=node_color,vmin=0.0,vmax=2.0, cmap=cmap)
plt.show()
Upvotes: 4