在 Python Matplotlib 的堆栈图中标记区域

8

我希望在 matplotlib 的 stackplot 中生成区域标签。如果只能标记边界的线,也可以接受。考虑以下示例:

import numpy as np
from matplotlib import pyplot as plt

fnx = lambda : np.random.randint(5, 50, 10)
x = np.arange(10)
y1, y2, y3 = fnx(), fnx(), fnx()
areaLabels=['area1','area2','area3']
fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3)
plt.show()

这将产生:enter image description here 但我想要的是这样的:enter image description here Matplotlib轮廓图具有此类型的标签功能(尽管在轮廓图的情况下,线条是带标签的)。
任何帮助(甚至是将我可能错过的帖子重定向)都将不胜感激。

对于这个问题的新手可能会感到困惑,因为文档表明支持标签,但是这似乎是一个谎言(https://github.com/matplotlib/matplotlib/issues/1943)。我收到了这个错误:`AttributeError: Unknown property labels`。 - Neil Traft
1个回答

5
啊,启发式算法。类似这样的吗?
import numpy as np
from matplotlib import pyplot as plt

length = 10
fnx = lambda : np.random.randint(5, 50, length)
x = np.arange(length)
y1, y2, y3 = fnx(), fnx(), fnx()
areaLabels=['area1','area2','area3']
fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3)

loc = y1.argmax()
ax.text(loc, y1[loc]*0.25, areaLabels[0])

loc = y2.argmax()
ax.text(loc, y1[loc] + y2[loc]*0.33, areaLabels[1])

loc = y3.argmax()
ax.text(loc, y1[loc] + y2[loc] + y3[loc]*0.75, areaLabels[2]) 

plt.show()

在测试运行中还算正常:

enter image description here

enter image description here

enter image description here

找到最佳的loc可能会更加花哨,也许需要找到平均值最高的x_n, x_(n+1)


非常聪明。我喜欢的是它有潜力应用于任意数量标签的循环中。即使它不完美,我发现您的图表比具有颜色键的可比图表更容易快速解释 - 特别是在堆叠> 10个绘图时。 - Docuemada
有些图表无法用这种方式标记--如果area2非常小,或者值上下跳动,水平面积不大。如果区域颜色与文本颜色相关联(文本边框带有区域颜色),可能会更清晰一些。 - cphlewis
是的,loc 应该在一个循环中为任意一系列 y 定义。留给读者作为练习! - cphlewis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接