0

I'm creating a Matplotlib figure, which I need to be quite wide (174 mm) and in .eps format. I also need it to be created with LaTeX for consistency with other figures. The problem is that the rightmost parts of the axes do not appear in the output figure, and the legend's box and handles also disappear.

The problem appears only if the figure if very wide, when I use LaTeX to produce it, and when I save it in .eps. The figure is as expected if it is thinner, if I save it in .pdf or .png, or if I just replace plt.savefig(...) with plt.show() and use Matplotlib's default viewer.

To be clearer, consider the following code.

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


x = np.linspace(-1, 1, 100)
y = np.exp(x)

mpl.rcParams['text.usetex'] = True

mm = 1/25.4
fig = plt.figure(figsize=(174*mm, 44*mm))

plt.plot(x, y, label='exponential')
plt.legend(loc='lower right')
plt.tight_layout()
plt.savefig('test.eps')

This outputs the following figure, where the legend handle and the rightmost part of the axes do not appear.

If it can help, the .eps file output by the above code is available here.

Vincent
  • 200
  • 2
  • 8

1 Answers1

0

TL;DR: an imperfect fix (figure size will be distorted) is to change the last two lines to:

plt.tight_layout(rect=(0, 0, 0.8, 1))
plt.savefig('test.eps', bbox_inches='tight')

Long story:

I had exactly the same issue yesterday: the right part of the x-axis in my figure was missing in .eps, but not .png or other formats. It seems to be related to the padding between the (sub)plot and the entire figure. Some other posts also find texts/legends could be lost, e.g. here and here.

In our case, the rightmost part goes wrong, so we can add a few space to the right to ensure we have enough space to draw the entire x axis and the legend box. That is, the current (normalised) horizontal dimension of our figure goes from 0 (the very left) to 1 (the very right), and we can reduce that to 0.9 or 0.8 (right, but not rightmost), and the extra 0.1 and 0.2 space allows for the axis and legend. The rect parameter in matplotlib.pyplot.tight_layout allows us to set the dimension/width of the plot.

We have to try a few values to see which one works. Another problem is that output figure size will be distorted after changing the above parameter, as said here. So the method here is really just a workaround instead of a perfect fix. A promising alternative is nschloe/tikzplotlib, which converts matplotlib figures to PGF/TikZ and works pretty well with LaTeX, though I haven't tried it yet.

harning
  • 1
  • 1