Nick
Nick

Reputation: 169

force matplotlib to fix the plot area

I have multiple plots that have the same x-axis. I would like to stack them in a report and have everything line up. However, matplotlib seems to resize them slightly based on the y tick label length.

Is it possible to force the plot area and location to remain the same across plots, relative to the pdf canvas to which I save it?

import numpy as np
import matplotlib.pyplot as plt
xs=np.arange(0.,2.,0.00001)
ys1=np.sin(xs*10.) #makes the long yticklabels
ys2=10.*np.sin(xs*10.)+10. #makes the short yticklabels

fig=plt.figure() #this plot ends up shifted right on the canvas
plt.plot(xs,ys1,linewidth=2.0)
plt.xlabel('x')
plt.ylabel('y')

fig=plt.figure() #this plot ends up further left on the canvas
plt.plot(xs,ys2,linewidth=2.0)
plt.xlabel('x')
plt.ylabel('y')

Upvotes: 2

Views: 2370

Answers (3)

Marty
Marty

Reputation: 99

I had the same problem. The following works for me.

Force the same figure width for all your plots around all your python scripts, for example:

fig1 = plt.figure(figsize=(12,6))
...
fig2 = plt.figure(figsize=(12,4))

And do not use (very important!):

fig.tight_layout()

Save the figure

plt.savefig('figure.png')

Plot areas should now be the same.

Upvotes: 1

mark jay
mark jay

Reputation: 1284

using subplots with the same x-axis should do the trick.

use sharex=True when you create the subplots. The benefit of sharex is that zooming or panning on 1 subplot will also auto-update on all subplots with shared axes.

import numpy as np
import matplotlib.pyplot as plt
xs = np.arange(0., 2., 0.00001)
ys1 = np.sin(xs * 10.)  # makes the long yticklabels
ys2 = 10. * np.sin(xs * 10.) + 10.  # makes the short yticklabels

fig, (ax1, ax2) = plt.subplots(2, sharex=True)
ax1.plot(xs, ys1, linewidth=2.0)
ax1.xlabel('x')
ax1.ylabel('y')

ax2.plot(xs, ys2, linewidth=2.0)
ax2.xlabel('x')
ax2.ylabel('y')
plt.show()

Upvotes: 0

DavidG
DavidG

Reputation: 25363

Your problem is a little unclear, however plotting them as subplots in the same figure should gaurantee that the axes and figure size of the two subplots will be alligned with each other

import numpy as np
import matplotlib.pyplot as plt

xs=np.arange(0.,2.,0.00001)
ys1=np.sin(xs*10.) #makes the long yticklabels
ys2=10.*np.sin(xs*10.)+10. #makes the short yticklabels

fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.plot(xs,ys1,linewidth=2.0)
ax1.set_xlabel('x')
ax1.set_ylabel('y')

ax2.plot(xs,ys2,linewidth=2.0)
ax2.set_xlabel('x')
ax2.set_ylabel('y')

plt.subplots_adjust(hspace=0.3)  # adjust spacing between plots    
plt.show()

This produces the following figure:

enter image description here

Upvotes: 2

Related Questions