Setting colors in draw_networkx and in matplotlib

I draw two types of shapes for which I want to align the colors:

  • The color of the nodes in the x.Graph network and
  • the color of pyplot.hlines in the normal plot.

Both shapes rely on a dictionary with the names node_names as keys, and ints on values ​​and matplotlib.colors.LinearSegmentedColormapcmap. As below:

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. In 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)

What 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, are not at all consistent with the result that 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 network graph, I get 3 clearly distinguishable colors, but for hlines they are almost indistinguishable.

What am I missing about how to nx.draw_networkxuse node_colorand cmap?

+4
1

[0,1] colormap. hline - networkx maptlotlib , min max. , networkx.draw_networkx node_color .

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()

enter image description here

+3

Source: https://habr.com/ru/post/1606256/


All Articles