打印和水平线之间的Matplotlib填充

2024-10-01 00:21:21 发布

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

抱歉,我无法发布我的真实数据或绘图。。所以我用MS画作了象形图

所以我有我的图-橙色线,作为一组X和Y值plt.plot(data_x, data_y)给出。 然后我添加了水平线-蓝线:plt.axvline(x=10)。 现在我想用这条线和我的图之间的颜色空间填充(最终,当值低于水平线时,用一种颜色填充,当值高于水平线时,用第二种颜色填充)

我尝试了plt.fillplt.fill_betweenplt.axhspan但是,我收到了关于维度问题或元素与序列的错误

有没有一个简单的方法可以做到这一点

enter image description here


Tags: 数据绘图dataplot颜色pltfillms
2条回答

你必须使用

import matplotlib.pyplot as plt
import numpy as np

data_x = np.arange(0.0, 2, 0.01)
data_y = np.sin(2 * np.pi * x)
data_y2 = 0

fig, ax = plt.subplots()

ax.fill_between(data_x, data_y, data_y2,
                where=data_y2 >= data_y,
                facecolor='green', interpolate=True)
ax.fill_between(data_x, data_y, data_y2,
                where=data_y2 <= data_y,
                facecolor='red', interpolate=True)

请注意,数据_y2必须是标量(例如0)或与数据_y具有相同形状

您可以在此处找到相关文档:

https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/fill_between_demo.html

https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.fill_between.html

是的,有一个where参数^{}用于执行此操作:

import matplotlib.pyplot as plt
import numpy as np

# make data
x = np.linspace(0, np.pi * 2, 300)
y = np.sin(x)

# init figure
fig, ax = plt.subplots()

# plot sin and line
ax.plot(x, y, color='orange')
ax.axhline(0)

# fill between hline and y, but use (y > 0) and (y < 0)
# to create boolean masks determining where to fill
ax.fill_between(x, y, where=(y > 0), color='orange', alpha=.3)
ax.fill_between(x, y, where=(y < 0), color='blue', alpha=.3)

enter image description here

相关问题 更多 >