timlin
timlin

Reputation: 13

matplotlib third axis label shifts

The following code is used to generate a figure with three y-axes, and the axes are labeled using scientific notations:

import numpy as np
import matplotlib.pyplot as plt

it = np.linspace(1, 101403, 101403, endpoint=True)

fig, ax = plt.subplots(figsize=(15,5))
fig.subplots_adjust(right=0.75)

twin1 = ax.twinx()
twin2 = ax.twinx()

twin2.spines["right"].set_position(("axes", 1.1)

ax.set_xlim(it[0], it[-1])
ax.set_ylim(0, 5e4)
ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
twin1.set_ylim(-0.5e7, 8.9e7)
twin2.set_ylim(0, 5e8)

ax.set_xlabel("X")
ax.set_ylabel("Y1")
twin1.set_ylabel("Y2")
twin2.set_ylabel("Y3")

ax.yaxis.label.set_color('blue')
twin1.yaxis.label.set_color('red')
twin2.yaxis.label.set_color('green')

tkw = dict(size=4, width=1.5)
ax.tick_params(axis='y', colors='blue', **tkw)
twin1.tick_params(axis='y', colors='red', **tkw)
twin2.tick_params(axis='y', colors='green', **tkw)
ax.tick_params(axis='x', **tkw)

twin2.spines['left'].set_edgecolor('blue')
twin1.spines['right'].set_edgecolor('red')
twin2.spines['right'].set_edgecolor('green')

plt.show()

After running the above code, the figure is like below:

1e4 and 1e7 are overlapping:

1e4 and 1e7 are overlapping

You may have noticed that the Y2 axis 1e4 and Y3 axis 1e7 are overlapping near the Y2 axis. How can I relocate 1e7 to the correct location, which is near the Y3 axis?

Upvotes: 1

Views: 536

Answers (1)

r-beginners
r-beginners

Reputation: 35115

This was my first experience with this phenomenon. I set ticklabel_format() for each of them, but it didn't help. I don't know if this is a problem with matplotlib or not, but I dealt with it by shifting the position directly. However, when I did that, the offset text was displayed on the x-axis as a side effect, so I forced it to be hidden. This is what I was referring to in this answer.

twin2.get_yaxis().get_offset_text().set_position((1.1,5.0)) 
ax.get_xaxis().get_offset_text().set_visible(False)

plt.show()

enter image description here

Upvotes: 1

Related Questions