How to move exponent label with spine in matplotlib twin_x plot?

Question:

I am using twin_x() to create a plot with shared twin axes. To create a MWE, I used an example matplotlib provides in their documentation also provided below in the code block.

If I make the y values of the twin axes that has the offset large, then the tick labels will have an exponential factor as desired. However, this value does not move with the spine.

How can I get the exponent factor label to move with the spline?

import matplotlib.pyplot as plt
import numpy as np

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

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

# Offset the right spine of twin2.  The ticks and label have already been
# placed on the right by twinx above.
twin2.spines.right.set_position(("axes", 1.2))

y = 1e6*np.linspace(1,2,3)

p1, = ax.plot([0, 1, 2], [0, 1, 2], "b-", label="Density")
p2, = twin1.plot([0, 1, 2], [0, 3, 2], "r-", label="Temperature")
p3, = twin2.plot([0, 1, 2], y, "g-", label="Velocity")

ax.set_xlabel("Distance")
ax.set_ylabel("Density")
twin1.set_ylabel("Temperature")
twin2.set_ylabel("Velocity")

ax.yaxis.label.set_color(p1.get_color())
twin1.yaxis.label.set_color(p2.get_color())
twin2.yaxis.label.set_color(p3.get_color())

tkw = dict(size=4, width=1.5)
ax.tick_params(axis='y', colors=p1.get_color(), **tkw)
twin1.tick_params(axis='y', colors=p2.get_color(), **tkw)
twin2.tick_params(axis='y', colors=p3.get_color(), **tkw)
ax.tick_params(axis='x', **tkw)

ax.legend(handles=[p1, p2, p3])

plt.show()

I have included a picture to help demonstrate. I want to move the 1e6 to be near the axis spine for velocity since it represents the velocity value.
Diagram of the label I want to move

Asked By: nikost

||

Answers:

You can do this by getting the text of the second axis and setting it to the position of the second axis. .set_position(1.2,1.1) can be set arbitrarily, you can adjust it yourself. This answer is based on this answer.

ax.legend(handles=[p1, p2, p3])
# update
twin2.get_yaxis().get_offset_text().set_position((1.2,1.1))

plt.show()

enter image description here

Answered By: r-beginners
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.