首页 > 解决方案 > 使用 matplotlib 突出显示堆栈图区域

问题描述

我想在堆栈图中突出显示一个堆栈的区域,例如 x 轴上的区域 4-5B仅使用另一种颜色或散列:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]

labels = ['A', 'B']

fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, labels=labels)
ax.legend()

在此处输入图像描述

标签: matplotlib

解决方案


手动添加的多边形。这可以同时着色和孵化。

import matplotlib.pyplot as plt
import matplotlib.patches as patches

x = [1, 2, 3, 4, 5]
y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]

labels = ['A', 'B']

fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, labels=labels)

p = patches.Polygon(((4.0, 3.0),(5.0,4.0),(5.0,13.0),(4.0,9.0)), fc='g', hatch='x')
ax.add_patch(p)

ax.legend()

在此处输入图像描述


推荐阅读