如何填充线连接的两组数据之间的区域?

时间:2019-03-17 11:56:11

标签: python matplotlib

我有两组数据,它们在图中像线条一样显示。如何在它们之间填充颜色区域?

import matplotlib.pyplot as plt
curve1, = plt.plot(xdata, ydata)
curve2, = plt.plot(xdata, ydata)

我尝试过:

x = np.arange(0,12,0.01)
plt.fill_between(x, curve1, curve2, color='yellow')

谢谢

1 个答案:

答案 0 :(得分:2)

您必须使用ydata作为fill_between的参数,而不是曲线。

直接使用ydata,或从curve1/2之类的ydata=curve1.get_ydata()对象中获取它们。

以下是根据docs改编而成的示例:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5, 5, 0.01)
y1 = -5*x*x + x + 10
y2 = 5*x*x + x

c1, = plt.plot(x, y1, color='black')
c2, = plt.plot(x, y2, color='black')

# If you want/have to get the data form the plots
# x = c1.get_xdata()
# y1 = c1.get_ydata()
# y2 = c2.get_ydata()

plt.fill_between(x, y1, y2, where=y2 >y1, facecolor='yellow', alpha=0.5)
plt.fill_between(x, y1, y2, where=y2 <=y1, facecolor='red', alpha=0.5)
plt.title('Fill Between')

plt.show()

最后您得到:

enter image description here