我想绘制一条从有限点开始延伸至无穷远的线。为简单起见,假设该线可以是水平的。我想绘制一条从 (0, 0)
到 (inf, 0)
的线。
使用hlines
:
>>> fig, ax = plt.subplots()
>>> ax.hlines(0, 0, np.inf)
.../python3.8/site-packages/matplotlib/axes/_base.py:2480: UserWarning: Warning: converting a masked element to nan.
xys = np.asarray(xys)
结果是一个空图。
axhline
有一个起始参数,但它是轴坐标而不是数据。 axline
存在类似问题。有没有一种方法可以绘制一条(水平)线,其一端位于数据坐标中,另一端位于无穷远处?
这背后的动机是我希望能够绘制一些累积概率,而无需将最后一个容器之后的数据设置为零,如下所示:Matplotlib cumulative histogram - vertical line placement bug or misinterpretation? 。我希望能够将线从最后一个 bin 延伸到 y=1.0 处的无穷大,而不是简单地结束直方图。
最佳答案
没有用于此目的的内置函数,但您可以在每次更改 x 限制时重新绘制到轴限制的线。
来自Axes
:
The events you can connect to are
'xlim_changed'
and'ylim_changed'
and the callback will be called withfunc(ax)
whereax
is the Axes instance.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
def hline_to_inf(ax, x, y):
line = ax.hlines(0, 0, ax.get_xlim()[1])
ax.callbacks.connect('xlim_changed',
lambda ax: line.set_paths([[[x, y], [ax.get_xlim()[1], y]]]))
hline_to_inf(ax, 0, 0)
plt.show()
关于python - 仅在 matplotlib 中水平线在一侧到无穷远,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73440977/