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

2024-04-29 15:32:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我试过了:

^{pr2}$

谢谢你


Tags: 数据import图形区域plotmatplotlib颜色as
1条回答
网友
1楼 · 发布于 2024-04-29 15:32:19

必须使用ydata作为^{}的参数,而不是曲线。在

要么直接使用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

相关问题 更多 >