python - 仅在 matplotlib 中水平线在一侧到无穷远

标签 python matplotlib

我想绘制一条从有限点开始延伸至无穷远的线。为简单起见,假设该线可以是水平的。我想绘制一条从 (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 with func(ax) where ax 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() 

enter image description here

关于python - 仅在 matplotlib 中水平线在一侧到无穷远,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73440977/

相关文章:

python - 无法从使用 Pandas 存储存档文件名称的 gzip 压缩文件中读取 csv 数据

python - 如何制作一个不是线性或对数的特定轴?

python - 如何使用 Tensorboard 检测消失和爆炸梯度?

python - 如何将 SimpleHTTPServer 代码更改为等效的生产服务器

python - 如何在 python 中使用 split() 时避免特定单词之间的空格

python - 如何快速比较列表和集合?

python - 查找回归平面并将其绘制到一组点

python - 通过直方图测量图像的颜色

python - 在 Matplotlib 中如何防止图像出现在屏幕上? Python

python - 在情节图例中写 $\sqrt(2)$ 而不是 1.414