Q:

drawing state diagrams / graphs in matplotlib with LaTeX?

is there a way to draw the following state diagram in matplotlib? 

Or instead to embed inside a matplotlib figure LaTeX code that draws these diagrams using a package like tikz? ideally I would like to annotate the edges and the nodes with LaTeX symbols/math so a solution that embeds LaTeX into a matplotlib figure would be the best.

A:

Here is a potential solution using tikz package.
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{arrows,shapes,automata,petri,positioning,calc}

\tikzset{
    place/.style={
        circle,
        thick,
        draw=black,
        fill=gray!50,
        minimum size=6mm,
    },
        state/.style={
        circle,
        thick,
        draw=blue!75,
        fill=blue!20,
        minimum size=6mm,
    },
}

\begin{document}

\begin{tikzpicture}[node distance=2cm and 1cm,>=stealth',auto, every place/.style={draw}]
    \node [place] (S1) {S1};
    \coordinate[node distance=1.1cm,left of=S1] (left-S1);
    \coordinate[node distance=1.1cm,right of=S1] (right-S1);

    \draw[->, thick] (left-S1) -- (S1);

    \node [place] (S2) [right=of S1] {S2};
    \node [place] (S3) [node distance=1.5cm,below =of right-S1] {S3};    
    \node [state,initial text=,accepting by double] (S4) [right=of S3] {S4};

    \path[->] (S1) edge [bend left] node {a} (S2);
    \path[->] (S2) edge [bend left] node {b} (S1);
    \path[->] (S2) edge [loop above] node {a} ();
    \path[->] (S3) edge [bend left] node {a} (S1);
    \path[->] (S2) edge [bend left] node {c} (S4);
    \path[->] (S3) edge [bend left] node {b} (S4);
    \path[->] (S4) edge [bend left] node {d} (S3);      
\end{tikzpicture}
\end{document}

Output

You could use math symbols in nodes and paths (arcs) labels by putting them between $ $ for example: \path[->] (S1) edge [bend left] node {$x^2$} (S2); and of course you can change the style the way you like thru \tikzset settings.

