Label Areas in Python Matplotlib stackplot

I would like to generate labels inside matplotlib stackplot areas. I would settle for labeling the string used to bind the scope. Let's consider an 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 gives: enter image description here

But I would like to create something like this:

enter image description here

Matplotlib contour plots have this type of labeling functionality (although lines are denoted in the case of an outline).

Any help (or even a mail redirection that I may have missed) is appreciated.

+3


source to share


1 answer


Ah, heuristic. Something like that?:

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 passes is good:

enter image description here



enter image description here

enter image description here

Finding the best loc

can be more attractive - perhaps the one x_n, x_(n+1)

with the highest average required .

+4


source







All Articles