在matplotlib中的两条垂直线之间填充 [英] Fill between two vertical lines in matplotlib
问题描述
我查看了matplotlib
文档中的示例,但是我不清楚如何我可以绘制出一条填充两条特定垂直线之间区域的图.
I went through the examples in 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.
例如,假设我要在x=0.2
和x=4
之间创建一个绘图(针对该绘图的整个y
范围).我应该使用fill_between
,fill
或fill_betweenx
吗?
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
?
我可以使用where
条件吗?
推荐答案
听起来像您想要 axvspan
(和 axhspan
)将填满整个y(或x)绘图范围,无论您如何缩放.
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
突出显示8到14之间的x区域:
For example, let's use axvspan
to highlight the x-region between 8 and 14:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, alpha=0.5, color='red')
plt.show()
您可以使用fill_betweenx
来执行此操作,但是矩形的范围(x和y)将在数据坐标中.使用axvspan
时,矩形的y范围默认为0和1,并且位于轴坐标中(换句话说,是图形高度的百分比).
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).
为说明这一点,让我们使矩形从高度的10%扩展到90%(而不是占据整个范围).尝试缩放或平移,请注意y范围在显示空间中固定,而x范围随缩放/平移而移动:
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:
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()
这篇关于在matplotlib中的两条垂直线之间填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!