问题描述
我创建了一个具有2个y轴的matplotlib图. y轴具有不同的比例,但是我希望刻度线和网格对齐.我正在从excel文件中提取数据,因此无法事先知道最大限制.我尝试了以下代码.
I created a matplotlib plot that has 2 y-axes. The y-axes have different scales, but I want the ticks and grid to be aligned. I am pulling the data from excel files, so there is no way to know the max limits beforehand. I have tried the following code.
# creates double-y axis
ax2 = ax1.twinx()
locs = ax1.yaxis.get_ticklocs()
ax2.set_yticks(locs)
现在的问题是ax2上的刻度不再具有标签.谁能给我一个很好的方法来使刻度线与不同的刻度对齐?
The problem now is that the ticks on ax2 do not have labels anymore. Can anyone give me a good way to align ticks with different scales?
推荐答案
对齐两个不同刻度的刻度位置将意味着放弃漂亮的自动刻度定位器,并将刻度设置为在副轴上的相同位置.原来的一个.
Aligning the tick locations of two different scales would mean to give up on the nice automatic tick locator and set the ticks to the same positions on the secondary axes as on the original one.
想法是使用一个函数在两个轴刻度之间建立关系,并将第二个轴的刻度设置在第一个轴的刻度上.
The idea is to establish a relation between the two axes scales using a function and set the ticks of the second axes at the positions of those of the first.
import matplotlib.pyplot as plt
import matplotlib.ticker
fig, ax = plt.subplots()
# creates double-y axis
ax2 = ax.twinx()
ax.plot(range(5), [1,2,3,4,5])
ax2.plot(range(6), [13,17,14,13,16,12])
ax.grid()
l = ax.get_ylim()
l2 = ax2.get_ylim()
f = lambda x : l2[0]+(x-l[0])/(l[1]-l[0])*(l2[1]-l2[0])
ticks = f(ax.get_yticks())
ax2.yaxis.set_major_locator(matplotlib.ticker.FixedLocator(ticks))
plt.show()
请注意,这是针对一般情况的解决方案,可能会导致用例上的标签完全不可读.如果您碰巧在轴范围上有更多的先验信息,则可能有更好的解决方案.
Note that this is a solution for the general case and it might result in totally unreadable labels depeding on the use case. If you happen to have more a priori information on the axes range, better solutions may be possible.
也可以参阅此问题以了解自动刻度位置的情况为了方便设置辅助轴的刻度位置,牺牲了第一根轴的数量.
Also see this question for a case where automatic tick locations of the first axes is sacrificed for an easier setting of the secondary axes tick locations.
这篇关于麻烦对齐matplotlib twinx轴的刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!