简体   繁体   English

matplotlib:对齐双Y轴

[英]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. 该问题的答案表明,我将使用set_ylim / get_ylim来对齐两个双轴。 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): 图形输出(在新窗口中打开图像):

在此处输入图片说明

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? 怎么了?

As tcaswell points out in a comment, plt.ylim() only affects one of the axes. 正如tcaswell在评论中指出的那样, plt.ylim()仅影响其中一个轴。 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. 它会按我想的那样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM