# How can I integrate matplotlib plots with pgfplots?

The python plotting library matplotlib will by default add margins to any plot that it generates. They can be reduced to a certain degree through some options of savefig(), namely bbox_inches='tight' and pad_inches=0. Even with those options, some margins will always remain, though.

If a plot generated by matplotlib is to be used in conjunction with pgfplots and the addplot graphics feature, those margins need to be predictable (and ideally non-existent).

Q: How can these margins be got rid of completely?

-

import numpy as np
import matplotlib.pyplot as pl

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig = pl.figure(figsize=(8,5))
ax = pl.gca()
pl.axis('off')
pl.plot(x, y)
pl.xlim(0,10)
pl.ylim(-1,1)

pl.subplots_adjust(left=0, right=1, top=1, bottom=0)
pl.savefig('out.pdf')


This generates a sine plot completely without margins. The resulting pdf can then be integrated into a pgfplots plot like this:

\documentclass{scrartcl}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
axis on top,
plot graphics/xmin=0,
plot graphics/xmax=10,
plot graphics/ymin=-1,
plot graphics/ymax=1,
enlargelimits=false]

This line extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) gave unexpected result in my case as well as the bbox_inches="tight". I replaced it by subplots_adjust(left=0., right=1., top=1., bottom=0.) and no bbox_inches option. –  Alfred M. Jun 12 '13 at 12:58