Skip to content
obtitus edited this page Jan 24, 2013 · 9 revisions

This page is for ways to make PythonTeX work with matplotlib more conveniently.

Saving figures and including it in your document

Say you have the following code in your document:

x = linspace(0, pi)
plt.plot(x, sin(x), label='sin(x)')
plt.plot(x, cos(x), label='cos(x)')

and you want to quickly view these graphs in your document, you could then call plt.legend and plt.savefig('foo.pdf') and then write the latex code to include a figure. To ease this process the following helper functions might be useful (modify them to suit your needs!):

global figCount
figCount = 0 # Used to give each figure a unique name
def savefig(name="", legend=False, fig=None):
  # Save current figure (or 'fig') to file using plt.savefig,
  # can be called with no arguments, it will then find a unique filename which is returned.
  if name.endswith('.pdf'):
    name = name[:-len('.pdf')]
  # fig
  if fig == None:
    fig = gcf()
  # Default name
  if name == "":
    global figCount
    name = "autoFig{}{}{}-{}".format(pytex.inputtype, pytex.inputsession, pytex.inputgroup, figCount)
    figCount += 1
  # Legend, put a nice legend on top of the figure (you may need to adjust this!)
  if legend and len(fig.gca().get_legend_handles_labels()[0]) != 0: # if axis has labels
    for ax in fig.axes:
      if ax.is_first_row():
        box = ax.get_position()
        ax.set_position([box.x0, box.y0, box.width, box.height*0.9])
    leg = ax.legend(loc="upper center", bbox_to_anchor=(0.5, 1.04), ncol=3, bbox_transform=fig.transFigure, frameon=False)
  plt.savefig(name+".pdf", fig)
  fig.clf()
  return name

def latexEnvironment(name, content='', option=''):
    # Just a simple helper function to write the \begin, \end latex block
    return r"""\begin{%s}%s                                                                                                                                                                                                                                                      
%s                                                                                                                                                                                                                                                                                 
\end{%s}""" % (name, option, content, name)

def latexFigure(name, caption='', label='', width=0.8):
  # Auto wraps 'name' in a latex figure environment.
  # width is a fraction of \textwidth
  content = '\\centering\n'
  content += "\\includegraphics[width=%f\\textwidth]{%s}\n" % (name, width)
  # label                                                                                                                                                                                                                                                                        
  if label == '':
    label = name
  if not(caption.strip().endswith('.')):
    caption += '.'

  content += "\\caption{%s}\n" % caption
  content += "\\label{pic:%s}" % label
  return latexEnvironment('figure', content, '[htp]')

The above code block can be included in a

\begin{pythontexcustomcode}[begin]
...
\end{pythontexcustomcode}

in your documents preamble, or you may store it in a file and import it the usual way. Say you have a "src" directory alongside your document and the above code is put in a file pythonPreamble.py:

\begin{pythontexcustomcode}[begin]{pylab}
sys.path.insert(0, "../src/")
from pythonPreamble import *
\end{pythontexcustomcode}

The above example may now be written as:

\begin{pylabcode}
x = linspace(0, pi)
plt.plot(x, sin(x), label='sin(x)')
plt.plot(x, cos(x), label='cos(x)')
fig = latexFigure(savefig())
\end{pylabcode}
\pylab{fig}

PGF backend

Matplotlib 1.2 has a new pgf backend.

Clone this wiki locally