fill_between() doesn`t work

可紊 提交于 2019-12-20 05:41:35

问题


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

What am I doing wrong?

Kind regards, Greem


回答1:


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.

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



来源:https://stackoverflow.com/questions/44557028/fill-between-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!