Label Areas in Python Matplotlib stackplot

China☆狼群 提交于 2019-12-23 10:24:30

问题


I would like to generate labels inside the areas of a matplotlib stackplot. I would settle for labeling a line used to bound the area. Consider the example:

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

This produces:

But I would like to produce something like this:

The matplotlib contour plots have this type of labeling functionality (though the lines are labeled in the case of the contour plot).

Any help (or even redirection to a post I might have missed) is appreciated.


回答1:


Ah, heuristics. Something like this?:

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

which in test runs is okayish:

Finding the best loc could be fancier -- maybe one wants the x_n, x_(n+1) with the highest average value.



来源:https://stackoverflow.com/questions/31573869/label-areas-in-python-matplotlib-stackplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!