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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:35:08  来源:igfitidea点击:

Fill between two vertical lines in matplotlib

pythonmatplotlib

提问by Amelio Vazquez-Reina

I went through the examplesin the matplotlibdocumentation, 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.2and x=4(for the full yrange of the plot). Should I use fill_between, fillor fill_betweenx?

例如,假设我想在x=0.2和之间创建一个图x=4(对于图的整个y范围)。我应该使用fill_between,fill还是fill_betweenx?

Can I use the wherecondition 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 axvspanto 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()

enter image description here

在此处输入图片说明

You could use fill_betweenxto 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()

enter image description here

在此处输入图片说明