简体   繁体   English

为什么 plt.hlines() 与 transform 一起使用时会调整 ylims,而 plt.plot() 不会?

[英]Why does plt.hlines() adjust ylims when used with transform, but plt.plot() does not?

I am trying to display a horizontal line at 20% of the y-axis using plt.hlines() with y=[0.2] and the transform=ax.get_xaxis_transform() argument.我正在尝试使用plt.hlines()y=[0.2]transform=ax.get_xaxis_transform()参数在 y 轴的 20% 处显示一条水平线。 When I do this the upper ylim of my plot is changed to 0.2 automatically.当我这样做时,我的情节的上部 ylim 会自动更改为 0.2。

I do not expect this behaviour because to my understanding the get_xaxis_transform() -transform should transform the y=[0.2] value to whatever corresponds to 20% of my y-axis.我不期望这种行为,因为据我了解get_xaxis_transform()应该将y=[0.2]值转换为对应于我的 y 轴的 20% 的值。 In particular because the hline is displayed at 20% but the limits are adjusted anyways.特别因为 hline 显示为 20%,但无论如何都会调整限制。

This does not happen when I perform the same operation using plt.plot() (rightmost plot).当我使用plt.plot() (最右边的图)执行相同的操作时,不会发生这种情况。 Here, the line stays at 20% of the y-axis even when interactively moving the visible area.在这里,即使交互式移动可见区域,这条线也会保持在 y 轴的 20% 处。

I am wondering why this happens and how I can avoid that hlines() adjusts the ylims when using it with the transform parameter.我想知道为什么会发生这种情况,以及如何避免hlines()在将其与 transform 参数一起使用时调整 ylims。

MWE: MWE:

import numpy as np
import matplotlib.pyplot as plt

y = np.random.rand(20)/100  # scale so all values should be far below 0.2
x = range(len(y))

# Scenario 0 (auto-scaled axes)
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3)
ax0.plot(x, y)
ax0.set(title='No horizontal lines drawn')

# Scenario 1
ax1.hlines(y=[0.2], xmin=5, xmax=15, transform=ax1.get_xaxis_transform(), color='black')
ax1.plot(x, y)
ax1.set(title='Using hlines()')

# Scenario 2
ax2.plot(x, y)
ax2.plot([5, 15], [0.2, 0.2], transform=ax2.get_xaxis_transform(), color='black')
ax2.set(title='Using plot()')

plt.show(block=True)

3个图,最左边不使用 hlines() 也不 plot() 显示水平线,中间一个使用 hlines() 并自动调整 y 轴,最右边一个使用 plot() 并且不调整 ylim

This happens because of a bug in matplotlib.这是因为 matplotlib 中的一个错误。 https://github.com/matplotlib/matplotlib/issues/23171 https://github.com/matplotlib/matplotlib/issues/23171

As you've discovered, using plt.plot() is a simple workaround.正如您所发现的,使用plt.plot()是一种简单的解决方法。

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

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