在 matplotlib 中的两条垂直线之间填充 [英] Fill between two vertical lines in matplotlib

查看:62
本文介绍了在 matplotlib 中的两条垂直线之间填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了 matplotlib 文档中的 examples,但它不是'我不清楚如何绘制填充两条特定垂直线之间区域的图.

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

我可以为此使用 where 条件吗?

解决方案

听起来你想要 axvspan,而不是函数之间的填充之一.不同之处在于 axvspan(和 axhspan) 将填充绘图的整个 y(或 x)范围,无论您如何缩放.

例如,让我们使用 axvspan 来突出显示 8 到 14 之间的 x 区域:

将 matplotlib.pyplot 导入为 plt图, ax = plt.subplots()ax.plot(范围(20))ax.axvspan(8, 14, alpha=0.5, color='red')plt.show()

您可以使用 fill_betweenx 来执行此操作,但矩形的范围(x 和 y)将位于数据坐标中.使用 axvspan,矩形的 y 范围默认为 0 和 1,并且位于 轴坐标(换句话说,绘图高度的百分比).

为了说明这一点,让我们让矩形从高度的 10% 延伸到 90%(而不是占据整个范围).尝试缩放或平移,并注意 y 范围表示在显示空间中固定,而 x 范围随着缩放/平移移动:

将 matplotlib.pyplot 导入为 plt图, ax = plt.subplots()ax.plot(范围(20))ax.axvspan(8, 14, ymin=0.1, ymax=0.9, alpha=0.5, color='red')plt.show()

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.

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?

Can I use the where condition for this?

解决方案

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.

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()

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).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆