Python 2.7 Графика анимации - определение цвета узла для кадра - PullRequest
0 голосов
/ 10 марта 2019

(Python 2.7) Это первый раз, когда я опубликовал в stackoverflow.Я пытаюсь анимировать график с помощью FuncAnimation, и цель состоит в том, чтобы определить цвета определенных узлов в каждом кадре.Я начинаю с импорта 649 узлов, а затем 751 ребер.График отображается нормально.Первоначальное изменение цвета узла было случайным и работало отлично.Я застрял, пытаясь удалить случайность и определить цвета для каждого кадра самостоятельно. Конечная цель - показать распространение сбоев по сети. Тем не менее, будет просто вручную определить цвет узла для 10 кадров.Любой совет будет наиболее ценным.Спасибо всем заранее.

# -*- coding: utf-8 -*-
"""
Spyder Editor
"""

import csv
import numpy as np
import matplotlib.pyplot as plt; plt.close('all')
import networkx as nx
from matplotlib.animation import FuncAnimation
from community import community_louvain

G = nx.Graph()
partition = community_louvain.best_partition(G)

with open('systems2_2.csv', 'r') as nodecsv: # Open the file (Just one column of names)                      
    nodereader = csv.reader(nodecsv) # Read the csv  
    mynodes = [n for n in nodereader][1:]                     
    total_nodes = len(mynodes) 
    node_names = [n[0] for n in mynodes] # Get a list of only the node names

with open('relations2_2.csv', 'r') as edgecsv: # Open the file (two columns of names)
    edgereader = csv.reader(edgecsv) # Read the csv     
    myedges = [tuple(e) for e in edgereader][1:] # Retrieve the data
    x=len(myedges)


''' Used to verify the number of nodes and edges were read correctly
'''
    print (str(total_nodes) +' nodes') 
    print (str(x) +' edges')

G.add_nodes_from(node_names)
G.add_edges_from(myedges)


def animate_nodes(G, node_colors, pos=None, *args, **kwargs):

    # define graph layout if None given
    if pos is None:
        pos = nx.spring_layout(G, k=1.9*(1/np.sqrt(len(G.nodes()))), iterations=25)

    nodes = nx.draw_networkx_nodes(G, pos, with_labels=True, node_color='b', *args, **kwargs)
    edges = nx.draw_networkx_edges(G, pos, *args, **kwargs)
    nx.draw_networkx_labels(G, pos, *args, **kwargs)

#    nx.draw(G, with_labels=True, node_color='b')

    plt.axis('off')

    def update(ii):
        nodes.set_array(node_colors[ii])
        return nodes,

    fig = plt.gcf()
    animation = FuncAnimation(fig, update, interval=40, frames=len(node_colors), blit=True) #len(node_colors)
    return animation

graph = G   
time_steps = 4

node_colors = np.random.randint(0, 1, size=(time_steps, total_nodes))

'''the code below does change the correct node in the correct frame
   but it uses a random color, not the color I try to specify
'''
color_map = [65535,255,16711680,65280 ] # These are the colors I want to use

node_colors[0][280]=color_map[0] 
node_colors[1][124]=color_map[1]
node_colors[2][280]=color_map[0]
node_colors[2][70]=color_map[3]
node_colors[3][280]=color_map[0]
node_colors[3][70]=color_map[0]
node_colors[3][364]=color_map[2]
node_colors[3][438]=color_map[2]
node_colors[3][11]=color_map[2]
node_colors[3][278]=color_map[0]


''' I used the following write statement to get a list of the nodes with an ID (count)
    This does identify the nodes correctly
'''

f=open("output.txt","w")
count = 0
for i in G.nodes:
        f.write(str(count)+ ' '+i+'\n')
        count = count+1
f.close()

animation = animate_nodes(graph, node_colors)
animation.save('test.html', writer='imagemagick', savefig_kwargs={'facecolor':'white'}, fps=1.0)

''' I needed to increase the size of the graph so the number of nodes I have will not
    be too close and overlapping. It is not perfect still, labels are difficult to read
    but with 649 nodes this is a big improvement
'''
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 60 #set hwidth
fig_size[1] = 40 #set hieght

plt.rcParams["figure.figsize"] = fig_size

print "Current size:", fig_size
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...