Python 在 matplotlib 中的两条垂直线之间填充
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23248435/
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
Fill between two vertical lines in matplotlib
提问by Amelio Vazquez-Reina
I went through the examplesin the matplotlib
documentation, but it wasn't clear to me how I can make a plot that fills the area between two specific vertical lines.
我在去例子中matplotlib
的文件,但它不是我清楚我怎样才能使填充两个特定的垂直线之间的区域的曲线图。
For example, say I want to create a plot between x=0.2
and x=4
(for the full y
range of the plot). Should I use fill_between
, fill
or fill_betweenx
?
例如,假设我想在x=0.2
和之间创建一个图x=4
(对于图的整个y
范围)。我应该使用fill_between
,fill
还是fill_betweenx
?
Can I use the where
condition for this?
我可以where
为此使用条件吗?
采纳答案by Joe Kington
It sounds like you want axvspan
, rather than one of the fill between functions. The differences is that axvspan
(and axhspan
) will fill up the entire y (or x) extent of the plot regardless of how you zoom.
这听起来像你想要的axvspan
,而不是函数之间的填充之一。不同之处在于axvspan
(和axhspan
) 将填满绘图的整个 y (或 x) 范围,无论您如何缩放。
For example, let's use axvspan
to highlight the x-region between 8 and 14:
例如,让我们使用axvspan
高亮显示 8 到 14 之间的 x 区域:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, alpha=0.5, color='red')
plt.show()
You could use fill_betweenx
to do this, but the extents (both x and y) of the rectangle would be in data coordinates. With axvspan
, the y-extents of the rectangle default to 0 and 1 and are in axes coordinates(in other words, percentages of the height of the plot).
您可以使用fill_betweenx
此方法,但矩形的范围(x 和 y)将在数据坐标中。使用axvspan
,矩形的 y 范围默认为 0 和 1,并且在轴坐标中(换句话说,绘图高度的百分比)。
To illustrate this, let's make the rectangle extend from 10% to 90% of the height (instead of taking up the full extent). Try zooming or panning, and notice that the y-extents say fixed in display space, while the x-extents move with the zoom/pan:
为了说明这一点,让我们让矩形从高度的 10% 延伸到 90%(而不是占据整个范围)。尝试缩放或平移,并注意 y 范围表示在显示空间中固定,而 x 范围随着缩放/平移移动:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, ymin=0.1, ymax=0.9, alpha=0.5, color='red')
plt.show()