我有两组数据显示为图形中的线条。如何在它们之间填充颜色区域?

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


谢谢

最佳答案

您必须将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()


最后,您将获得:

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

10-04 18:32