fill_between()不起作用 [英] fill_between() doesn`t work

查看:166
本文介绍了fill_between()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的图表存在这个小问题.我想填充两条半垂直线之间的区域,如下所示(青色和灰色):

I have this tiny problem with a chart I am working on. I'd like to fill the area between 2 semi-vertical lines as shown below (teal and grey ones):

但是,当我使用以下代码时,我什么也没得到:

However, when I use the following code, I don`t get anything:

plt.fill_between(x, y_1, y_2, facecolor = 'red')

我在做什么错了?

亲切的问候, 格蕾姆

推荐答案

两行的x变量的数据范围是完全分开的,因此,甚至没有一个点可以在y方向进行填充.

The data ranges of the x variable of both lines are completely seperate, so there is not even a single point at which a fill could be done in y direction.

您可能想改为填写x方向,这可以使用fill_betweenx完成.现在的问题是,两行的y值都不同.因此,需要对它们进行插值,以使fill_betweenx可以将相同的y值用于两条曲线之间的填充,这些曲线最初对于不同的x值具有不同的y值.

You may want to fill in x direction instead, which could be done using fill_betweenx. The problem is now that the y values of both lines are different. One would therefore need to interpolate them such that the fill_betweenx can use the same y values for the fill between the two curves that initially have different y values for different x values.

import numpy as np
import matplotlib.pyplot as plt

x1 = np.array([1.00, 1.20, 1.30, 1.55, 1.60])
x2 = np.array([1.82, 1.91, 2.14, 2.26, 2.34])

y1 = np.array([1.03, 1.20, 1.28, 1.42, 1.71])
y2 = np.array([0.90, 1.10, 1.31, 1.42, 1.58])

fig, ax= plt.subplots()
ax.plot(x1,y1, color="indigo")
ax.plot(x2,y2, color="crimson")

yi = np.sort(np.c_[y1,y2].flatten()) 
x1i = np.interp(yi, y1, x1)
x2i = np.interp(yi, y2, x2)

ax.fill_betweenx(yi, x1i, x2i, color="lemonchiffon")

plt.show()

上述解决方案的替代方法是绘制一条以两条线的坐标为其边缘点的多边形.

The alternative to the above solution could be to draw a polgon, with the coordinates of both lines as its edge points.

import numpy as np
import matplotlib.pyplot as plt

x1 = np.array([1.00, 1.20, 1.30, 1.55, 1.60])
x2 = np.array([1.82, 1.91, 2.14, 2.26, 2.34])

y1 = np.array([1.03, 1.20, 1.28, 1.42, 1.71])
y2 = np.array([0.90, 1.10, 1.31, 1.42, 1.58])

fig, ax= plt.subplots()
ax.plot(x1,y1, color="indigo")
ax.plot(x2,y2, color="crimson")

x = np.append(x1,x2[::-1])
y = np.append(y1,y2[::-1])

p = plt.Polygon(np.c_[x,y], color="lemonchiffon")
ax.add_patch(p)

plt.show()

这篇关于fill_between()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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