Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

python - matplotlib align twinx tick marks

Is it possible to make a plot with two independent y-axes such that the tick marks align?

Below is an example of half of the solution. I've doubled the y-axis using twinx, but the tick marks aren't aligned and the gridlines form an awkward pattern on the plot. Is there a way to make the tick marks share the same positions, but correspond to different y-values? In the example below, I would like the tick mark for 5 on the left to be at the same vertical position as the tick mark for 6 on the right.

import numpy as np

a = np.random.normal(10, 3, size=20)
b = np.random.normal(20, 5, size=40)

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.hist(a)
ax2.hist(b)

histograms

The overarching point of this exercise is to make the grid lines overlap for the two axes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to manually set the yticks as it stands these are automatically calculated resulting in a variation. Adding something like this:

ax1.set_yticks(np.linspace(ax1.get_ybound()[0], ax1.get_ybound()[1], 5))
ax2.set_yticks(np.linspace(ax2.get_ybound()[0], ax2.get_ybound()[1], 5))

where we set the ytick locations using an array of 5 points between the bounds of the axis. Since you have a histogram you could just set the lower value to zero in each case, and you may want to have the upper bound somewhat larger, so I would instead have

ax1.set_yticks(np.linspace(0, ax1.get_ybound()[1]+1, 5))
ax2.set_yticks(np.linspace(0, ax2.get_ybound()[1]+1, 5))

Giving a plot (with a change of color and transparency (alpha) for clarity):

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...