Python 如何在matplotlib中的给定图上绘制垂直线?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24988448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to draw vertical lines on a given plot in matplotlib?
提问by Francis
Given a plot of signal in time representation, how to draw lines marking corresponding time index?
给定时间表示中的信号图,如何绘制标记相应时间索引的线?
Specifically, given a signal plot with time index ranging from 0 to 2.6(s), I want to draw vertical red lines indicating corresponding time index for the list [0.22058956, 0.33088437, 2.20589566]
, how can I do it?
具体来说,给定时间索引范围为 0 到 2.6(s) 的信号图,我想绘制垂直红线,指示列表的相应时间索引[0.22058956, 0.33088437, 2.20589566]
,我该怎么做?
采纳答案by Gabriel
The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline
添加将覆盖整个绘图窗口的垂直线而无需指定其实际高度的标准方法是 plt.axvline
import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)
OR
或者
xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
plt.axvline(x=xc)
You can use many of the keywords available for other plot commands (e.g. color
, linestyle
, linewidth
...). You can pass in keyword arguments ymin
and ymax
if you like in axes corrdinates (e.g. ymin=0.25
, ymax=0.75
will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline
) and rectangles (axvspan
).
您可以使用许多可用于其他绘图命令的关键字(例如color
, linestyle
, linewidth
...)。你可以传入关键字参数ymin
,ymax
如果你喜欢坐标轴(例如ymin=0.25
,ymax=0.75
将覆盖图的中间部分)。水平线(axhline
)和矩形(axvspan
)都有对应的函数。
回答by Qina Yan
For multiple lines
对于多行
xposition = [0.3, 0.4, 0.45]
for xc in xposition:
plt.axvline(x=xc, color='k', linestyle='--')
回答by Peter
Calling axvline in a loop, as others have suggested, works, but can be inconvenient because
正如其他人所建议的那样,在循环中调用 axvline 是可行的,但可能不方便,因为
- Each line is a separate plot object, which causes things to be very slow when you have many lines.
- When you create the legend each line has a new entry, which may not be what you want.
- 每条线都是一个单独的绘图对象,当你有很多线时,这会导致事情变得非常缓慢。
- 创建图例时,每行都有一个新条目,这可能不是您想要的。
Instead you can use the following convenience functions which create all the lines as a single plot object:
相反,您可以使用以下便捷函数将所有线条创建为单个绘图对象:
import matplotlib.pyplot as plt
import numpy as np
def axhlines(ys, ax=None, **plot_kwargs):
"""
Draw horizontal lines across plot
:param ys: A scalar, list, or 1D array of vertical offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
lims = ax.get_xlim()
y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
return plot
def axvlines(xs, ax=None, **plot_kwargs):
"""
Draw vertical lines on plot
:param xs: A scalar, list, or 1D array of horizontal offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
lims = ax.get_ylim()
x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
return plot
回答by seralouk
If someone wants to add a legend
and/or colors
to some vertical lines, then use this:
如果有人想添加一个legend
和/或colors
一些垂直线,然后使用这个:
import matplotlib.pyplot as plt
# x coordinates for the lines
xcoords = [0.1, 0.3, 0.5]
# colors for the lines
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()
Results:
结果:
回答by Sheldore
In addition to the plt.axvline
and plt.plot((x1, x2), (y1, y2))
OR plt.plot([x1, x2], [y1, y2])
as provided in the answers above, one can also use
除了上面答案中提供的plt.axvline
和plt.plot((x1, x2), (y1, y2))
ORplt.plot([x1, x2], [y1, y2])
之外,还可以使用
plt.vlines(x_pos, ymin=y1, ymax=y2)
to plot a vertical line at x_pos
spanning from y1
to y2
where the values y1
and y2
are in absolute data coordinates.
在绘制的垂直线x_pos
从跨越y1
到y2
其中的值y1
和y2
在绝对坐标数据。