Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Latex Citation in matplotlib Legend

I am generating figures for a technical paper using Python with matplotlib. Is there a way to include a Latex/Bibtex citation in the legend text? Ideally I would like a solution something like the following but haven't found anything that works:

import numpy as np
import matplotlib as mp
import matplotlib.pyplot as plt

x = np.linspace(0., 1., num=100)
y = x**2

plt.plot(x, y, label=r'Data \cite{<key>}')
plt.legend(loc=0)
plt.show()
like image 335
LWhitson2 Avatar asked Aug 01 '13 18:08

LWhitson2


People also ask

What is Bbox_to_anchor?

bbox_to_anchor=[x0, y0] will create a bounding box with lower left corner at position [x0, y0] . The extend of the bounding box is zero - being equivalent to bbox_to_anchor=[x0, y0, 0, 0] . The legend will then be placed 'inside' this box and overlapp it according to the specified loc parameter.


2 Answers

This can be done using the matplotlib pgf backend for python. The python file for generating the graph is as follows:

import numpy as np
import matplotlib as mpl
mpl.use('pgf')
import matplotlib.pyplot as plt

x = np.linspace(0., 1., num=100)
y = x**2

plt.plot(x, y, label=r'Data \cite{<key>}')
plt.legend(loc=0)
plt.savefig('fig.pgf')

The pgf file can then be utilized in a latex paper as such:

\documentclass[letterpaper,10pt]{article}
\usepackage[utf8x]{inputenc}
\usepackage{pgf}

\begin{document}

  \begin{figure}
    \centering
    \input{fig.pgf}
    \caption{Test Figure}
  \end{figure}

\end{document}

Whenever the latex file is compiled, the citation in the legend will be updated automatically.

like image 129
LWhitson2 Avatar answered Sep 21 '22 20:09

LWhitson2


Check out tikzplotlib (a project of mine). You can use it to save matplotlib figures as TikZ/Pgfplots which retains a lot of informations and which are very easily editable. Adding a BibTeX citation as a legend is no problem at all.

like image 40
Nico Schlömer Avatar answered Sep 20 '22 20:09

Nico Schlömer