How to visually animate Markov chains in Python?

Viewed 869

I want to "visually" animate Markov chains like here : http://markov.yoriz.co.uk/ but using Python instead of html css and javascript.

I don't know if there is any library that makes this easy, till now I managed to make a visual representation of Markov chains using Networkx library like in the figure below, but couldn't get it to be animated (or simulated)

Here is my code so far:

from networkx.drawing.nx_pydot import write_dot
import networkx as nx
import matplotlib.pyplot as plt

states = [(0, 0),
          (1, 0),
          (2, 0),]


Q = [[5, 5, 0.4],
     [1, 2, 3],
     [4, 0.7, 0]
     ]


G = nx.MultiDiGraph()
labels={}
edge_labels={}

for i, origin_state in enumerate(states):
    for j, destination_state in enumerate(states):
        rate = Q[i][j]
        if rate > 0:
            G.add_edge(origin_state, destination_state, weight=rate, label="{:.02f}".format(rate))
            edge_labels[(origin_state, destination_state)] = label="{:.02f}".format(rate)



plt.figure(figsize=(10,7))
node_size = 200
pos = {state:list(state) for state in states}
nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5)
nx.draw_networkx_labels(G, pos, font_weight=2)
nx.draw_networkx_edge_labels(G, pos, edge_labels)
plt.axis('off');
plt.show()

write_dot(G, 'mc.dot')

from subprocess import check_call
nfile = 'w.png' 
check_call(['dot', '-Tpng', 'mc.dot', '-o', nfile])

import matplotlib.image as mpimg
img = mpimg.imread(nfile)
plt.axis('off')
plt.imshow(img)
plt.show()

enter image description here

0 Answers
Related