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. When I do this the upper ylim of my plot is changed to 0.2 automatically.
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. In particular because the hline is displayed at 20% but the limits are adjusted anyways.
This does not happen when I perform the same operation using plt.plot()
(rightmost plot). Here, the line stays at 20% of the y-axis even when interactively moving the visible area.
I am wondering why this happens and how I can avoid that hlines()
adjusts the ylims when using it with the transform parameter.
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)
This happens because of a bug in matplotlib. https://github.com/matplotlib/matplotlib/issues/23171
As you've discovered, using plt.plot()
is a simple workaround.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.