简体   繁体   English

使用 matplotlib 绘制随机生成的图形

[英]Drawing randomly generated graph with matplotlib

I found this script and modified it to color a graph that I randomly generate.我找到了这个脚本并对其进行了修改,以便为我随机生成的图表着色。 I now want to draw that graph with the color that the script assigns to the vertices.我现在想用脚本分配给顶点的颜色来绘制该图。 I managed to draw the graph with networkx which uses matplotlib but I don't know how to draw it using the colors assigned by the script.我设法使用使用matplotlib的 networkx 绘制图形,但我不知道如何使用脚本分配的 colors 绘制它。 This is my script:这是我的脚本:

import networkx as nx 
import matplotlib.pyplot as plt
from random import sample
from random import randrange
# Python3 program to implement greedy
# algorithm for graph coloring

def addEdge(adj, v, w):
    
    adj[v].append(w)
    
    # Note: the graph is undirected
    adj[w].append(v)
    return adj

# Assigns colors (starting from 0) to all
# vertices and prints the assignment of colors
def greedyColoring(adj, V):
    
    result = [-1] * V

    # Assign the first color to first vertex
    result[0] = 0;


    # A temporary array to store the available colors.
    # True value of available[cr] would mean that the
    # color cr is assigned to one of its adjacent vertices
    available = [False] * V

    # Assign colors to remaining V-1 vertices
    for u in range(1, V):
        
        # Process all adjacent vertices and
        # flag their colors as unavailable
        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = True

        # Find the first available color
        cr = 0
        while cr < V:
            if (available[cr] == False):
                break
            
            cr += 1
            
        # Assign the found color
        result[u] = cr

        # Reset the values back to false
        # for the next iteration
        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = False

    # Print the result
    for u in range(V):
        print("Vertex", u, " ---> Color", result[u])


     
q = [0,1,2,3,4]
d = {i: sample([j for j in q if i != j], randrange(1, len(q) - 1))
     for i in q}
print(d)
greedyColoring([node for node in d.values()], 5)

options = {
    'node_color': 'red',
    'node_size': 4,
    'width': .1,
}


G = nx.Graph()
def passacolorsNx():
    for k in d:
        for j in d[k]:
            G.add_node(j)
            G.add_edges_from([(k, j)])
passcolorsNx()

subax1 = plt.subplot(121)
nx.draw(G, **options)
plt.show()

As you can see, to pass the randomly generated graph to networkx I created the function如您所见,为了将随机生成的图传递给 networkx,我创建了 function

Passcolorsnx()

You can use a node-color map.您可以使用节点颜色 map。 Here's the modified code from the snippet you posted (note that now you need to return the result to store the colors).这是您发布的代码段中的修改代码(请注意,现在您需要返回result以存储颜色)。 Fixed the typo in passcolorsNx .修复了passcolorsNx中的错字。 You can modify result to contain actual color names if you want to override the default colorscheme.如果要覆盖默认颜色方案,可以修改result以包含实际颜色名称。

import networkx as nx 
import matplotlib.pyplot as plt
from random import sample
from random import randrange
# Python3 program to implement greedy
# algorithm for graph coloring

def addEdge(adj, v, w):
    
    adj[v].append(w)
    
    # Note: the graph is undirected
    adj[w].append(v)
    return adj

# Assigns colors (starting from 0) to all
# vertices and prints the assignment of colors
def greedyColoring(adj, V):
    
    result = [-1] * V

    # Assign the first color to first vertex
    result[0] = 0;


    # A temporary array to store the available colors.
    # True value of available[cr] would mean that the
    # color cr is assigned to one of its adjacent vertices
    available = [False] * V

    # Assign colors to remaining V-1 vertices
    for u in range(1, V):
        
        # Process all adjacent vertices and
        # flag their colors as unavailable
        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = True

        # Find the first available color
        cr = 0
        while cr < V:
            if (available[cr] == False):
                break
            
            cr += 1
            
        # Assign the found color
        result[u] = cr

        # Reset the values back to false
        # for the next iteration
        for i in adj[u]:
            if (result[i] != -1):
                available[result[i]] = False

    # Print the result
    for u in range(V):
        print("Vertex", u, " ---> Color", result[u])
    return result


     
q = [0,1,2,3,4]
d = {i: sample([j for j in q if i != j], randrange(1, len(q) - 1))
     for i in q}
print(d)
result = greedyColoring([node for node in d.values()], 5)

options = {
    'node_color': result,
    'node_size': 4,
    'width': .1,
}


G = nx.Graph()
def passcolorsNx():
    for k in d:
        G.add_node(k)
        for j in d[k]:
            G.add_edge(k, j)
passcolorsNx()

subax1 = plt.subplot(121)
nx.draw(G, **options)
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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