How to output colored graph (each vertex has its own color) using matplotlib
library for python? Is there any method to adjust specific color to each vertex?
Code example without using colors:
import networkx as nx
import matplotlib.pyplot as plt
class Graph:
def __init__(self, edges):
self._edges = edges
def visualize(self):
vg = nx.Graph()
vg.add_edges_from(self._edges)
nx.draw_networkx(vg)
plt.show()
nodes = [['A', 'B'], ['A', 'C'], ['B', 'D'], ['C', 'D'],
['C', 'E'], ['D', 'F'], ['E', 'F']]
G = Graph(nodes)
G.visualize()
That's how i want to see it:
CodePudding user response:
I'm not sure if you want to change colors only for this case or make it more flexible - using list comprehension, but AFAIK draw_networkx
has a parameter which takes a list of strings or for RGB
tuple of floats, so only what you can do is prepare a list of colors:
import networkx as nx
import matplotlib.pyplot as plt
class Graph:
def __init__(self, edges, colors):
self._edges = edges
self._colors = colors
def visualize(self):
vg = nx.Graph()
vg.add_edges_from(self._edges)
nx.draw_networkx(vg, node_color=self._colors)
plt.show()
nodes = [['A', 'B'], ['A', 'C'], ['B', 'D'], ['C', 'D'],
['C', 'E'], ['D', 'F'], ['E', 'F']]
colors = ['green', 'red', 'red', 'green', 'green', 'red']
G = Graph(nodes, colors)
G.visualize()