bzm3r
bzm3r

Reputation: 4596

matplotlib: Aligning twin y-axes

The answer to this question suggests that I play around with the set_ylim/get_ylim in order to align two twin axes. However, this does not seem to be working out for me.

Code snippet:

fig, ax1 = plt.subplots()

yLim = [minY, maxY]
xLim = [0, 0.01]

for x in analysisNumbers:
    ax1.plot(getData(x), vCoords, **getStyle(x))

ax1.set_yticks(vCoords)
ax1.grid(True, which='major')


ax2 = ax1.twinx()
ax2.set_yticks(ax1.get_yticks())
ax2.set_ylim(ax1.get_ylim())
ax2.set_ylim(ax1.get_ylim())

plt.xlim(xLim[0], xLim[1])
plt.ylim(yLim[0], yLim[1])

plt.minorticks_on()

plt.show()

Graph output (open image in a new window):

enter image description here

The twin axes should be the same, but they are not. Their labels are the same, but their alignment is not (see that the zeroes do not line up). What's wrong?

Upvotes: 0

Views: 3227

Answers (1)

drevicko
drevicko

Reputation: 15180

As tcaswell points out in a comment, plt.ylim() only affects one of the axes. If you replace these lines:

ax2.set_ylim(ax1.get_ylim())
ax2.set_ylim(ax1.get_ylim())

plt.xlim(xLim[0], xLim[1])
plt.ylim(yLim[0], yLim[1])

with this:

ax1.set_ylim(yLim[0], yLim[1])
ax2.set_ylim(ax1.get_ylim())

plt.xlim(xLim[0], xLim[1])

It'll work as I'm guessing you intended.

Upvotes: 1

Related Questions