简体   繁体   中英

Set different node colors in a random networkx graph

I have created an Erdős-Rényi random graph with 100 nodes, but I want to draw this graph with different node colors. For example, I want to have 25 nodes colored red, 25 nodes colored blue, and so on. Can you help me, how can I achieve this in my code?

>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G = nx.erdos_renyi_graph (100,0.02)
>>> nx.draw(G, node_color=range(100), node_size=800, cmap=plt.cm.Blues)

This can be achieved using colors from the matplotlib colors API . From the networkx.draw docs, we can see the description of node_color is as follows:

node_color (color or array of colors (default='#1f78b4'))

Node color. Can be a single color or a sequence of colors with the same length as nodelist. Color can be string, or rgb (or rgba) tuple of floats from 0-1. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details.

So in your case, you want 25 nodes to be one color, 25 to be another, etc. For this, we can use colors = ['r','b','y','c']*25 to define the array of colors, and then pass this to nx.draw as in the following code.

Code:

import networkx as nx
import matplotlib.pyplot as plt
G = nx.erdos_renyi_graph (100,0.02)

colors = ['r','b','y','c']*25

plt.figure(figsize=(10,10))
nx.draw(G, node_size=400, node_color=colors, dpi=500)

Output:

输出图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM