【问题标题】:Matplotlib Forcing Dashed Line to Touch AxisMatplotlib 强制虚线触摸轴
【发布时间】:2026-01-22 15:55:03
【问题描述】:

有没有办法强制绘制曲线的虚线接触两个轴(顶部和底部)?具体来说,我正在寻找一种方法来指定破折号的开始位置(xstart,ystart)和结束位置(xend,yend),以便我可以强制它接触轴。这是一个显示问题的示例:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 5, 10)
y = np.power(x,3.0)+80

plt.plot(x,y+5, '--')
plt.axis(xmin=0,xmax=5,ymin=100,ymax=150)

【问题讨论】:

  • 尝试ylim xlim 任意设置与数据相关的截距。
  • 这不是让绘图窗口变小吗?我宁愿不必牺牲我的情节范围来让它发挥作用。
  • 那我可能误会了。你能给出一个完整的可执行文件但最小的例子来说明这个问题吗?
  • 我进行了编辑以包含代码。我希望虚线在 y=100 处接触底部 y 轴,在 y=150 处接触顶部 y 轴。
  • 查看此链接:*.com/questions/14710221/… 以获得更精细的破折号控制以及在该示例中线条是如何接触的。所以我错了,破折号样式应始终以破折号“on”开头,并且应符合您的要求。

标签: python matplotlib plot line


【解决方案1】:

根据 roadrunner66 的评论,我组装了一个适合我的示例

l, = plt.plot(x,y+5)
l.set_dashes([5,2])
plt.axis(xmin=0,xmax=5,ymin=100,ymax=150)

如果您想自动执行此操作,我想您还需要知道线条的长度才能计算出正确的破折号。

要获得display coordinates 中的行长,可以这样做

xl,yl=l.get_xydata().T
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()

# Filter out the points outside the range & replace them with a point on the axis
m = ((xl >= xmin) & (xl <= xmax)) & ((yl >= ymin) & (yl <= ymax))
x = np.concatenate([[xmin], xl[m], [xmax]])
y = np.concatenate([[ymin], yl[m], [ymax]])
xt, yt = ax.transData.transform(np.vstack([xl,yl]).T).T
length = np.sum( np.sqrt((xt[1:] - xt[:-1])**2 + (yt[1:] - yt[:-1])**2))

现在给定这个长度,我们可以计算出合理的刻度长度和间距

length = np.sum( np.sqrt((x[1:] - x[:-1])**2 + (y[1:] - y[:-1])**2))
tickl = 5.
minspace = 2.
i = int(length / (tickl + minspace))
space = length / i - tickl # since length = i * (space + tickl)
print space

这给了我 2.39086935951 的值,所以 2 的猜测还不错。

【讨论】:

  • 您也可以使用plt.plot(x, y, linestyle=(0, [5, 2]) 执行此操作。 0 是“偏移量”(“开始”在循环中有多少像素,并且在 2.x 和 master 分支上正常工作(但在任何已发布的 mpl 版本中都没有:/)
  • @tacaswell 现在可以在已发布的版本中使用!您绝对应该向该线程提交答案,因为它更简单地解决了问题。它应该是公认的解决方案。