0

以下のページを参考にノードの色のα値を変化させたものをGIFにしたいのですが、うまくいきません。

Using NetworkX with matplotlib.ArtistAnimation - Stack Overflow

import numpy as np
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

G = nx.Graph()
G.add_edges_from([(0,1),(1,2),(2,0)])
fig = plt.figure(figsize=(8,8))
pos= {0: (3, 3), 
        1: (2, 2), 2: (4, 2)}
nc = np.random.random(3)
nodes = nx.draw_networkx_nodes(G,pos)
edges = nx.draw_networkx_edges(G,pos) 

def update(n):
    random.seed(1)
    nc = np.random.random(3) #ここがうまくいきません。
    nodes.set_array(nc) #ここの処理が?
    return nodes,

anim = FuncAnimation(fig, update, interval=50, blit=True)

例えば、縦がノード数、横がRGB+アルファ値の行列が与えられた場合、この4番目のアルファ値だけを時間ごとに変化させたいのです。

nc = [[0.13436424, 0.84743374, 0.76377462, 0.38538581],
      [0.25506903, 0.49543509, 0.44949106, 0.00395534],
      [0.65159297, 0.78872335, 0.09385959, 0.00395534]]
    nx.draw(G,pos,node_color=nc)

その場合、nodes.set_array(nc) の処理がよくわからないのですが、どのように書けば良いのでしょうかご教授願います。よろしくお願いいたします。

1 件の回答 1

2

アルファ値が時間経過とともにどのように変化するのかわからないのですが、ここではランダムに変化するものとしました。

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

G = nx.Graph()
G.add_edges_from([(0,1),(1,2),(2,0)])
pos= {0:(3,3), 1:(2,2), 2:(4,2)}

nc = [[0.13436424, 0.84743374, 0.76377462, 0.38538581],
      [0.25506903, 0.49543509, 0.44949106, 0.00395534],
      [0.65159297, 0.78872335, 0.09385959, 0.00395534]]

fig, ax = plt.subplots(figsize=(8,8))

def update(n):
  ax.clear()
  nc[0][3] = np.random.random(1)[0]
  nc[1][3] = np.random.random(1)[0]
  nc[2][3] = np.random.random(1)[0]
  nodes = nx.draw_networkx_nodes(G, pos, node_color=nc, ax=ax)
  edges = nx.draw_networkx_edges(G, pos, ax=ax)

anim = FuncAnimation(fig, update, interval=250)
#anim.save('animation.gif', writer='pillow')
plt.show()
1
  • ありがとうございます!
    – 0018
    2021年2月20日 16:09

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。