# Visualising Markov Chains with NetworkX

I’ve written quite a few blog posts about Markov chains (it occupies a central
role in quite a lot of my research). In general I visualise 1 or 2 dimensional
chains using Tikz (the LaTeX package) sometimes
scripting the drawing of these using Python **but** in this post I’ll describe
how to use the awesome networkx package to
represent the chains.

For all of this we’re going to need the following three imports:

Let’s consider the Markov Chain I describe in this post about waiting times in a tandem queue. You can see an image of it (drawn in Tikz) below:

As is described in that post, we’re dealing with a two dimensional chain and without going in to the details, the states are given by:

and the transition matrix \(Q\) by:

To build the `networkx`

graph we will use our states as nodes and have edges
labeled by the corresponding values of \(Q\) (ignoring edges that would
correspond to a value of 0). **The neat thing about networkx is that it
allows you to have any Python instance as a node**:

Now we can draw the chain:

You can see the result here:

As you can see in the networkx documentatin:

Yes, it is ugly but drawing proper arrows with Matplotlib this way is tricky.

So instead I’m going to write this to a
`.dot`

file:

Once we’ve done that we have a standard network file format, so we can use the command line to convert that to whatever format we want, here I’m creating the png file below:

The `.dot`

file is a standard graph
format but you can also just open up the
`.ps`

file in whatever you want and
modify the image. Here it is in inkscape:

Even if the above is not as immediately esthetically pleasing as a nice Tikz diagram (but how could it be?) it’s a nice quick and easy way to visualise a Markov chain as you’re working on it.