Custom legend in python

I have this plot in which some areas between the curves are filled by definition. Is there any way to include them in the legend? Especially where these filled areas overlap and a new and different color appears.

Or is it possible to define an arbitrary legend, regardless of the given curves? enter image description here

+4
source share
2 answers

Using fill_bettweento build your data will automatically include the filled area in the legend.

To include areas where two datasets overlap, you can combine legend descriptors from both datasets into one description descriptor.

, -.

, , , , .

. MWE, :

import matplotlib.pyplot as plt
import numpy as np

plt.close('all')

# Gererate some datas:
x = np.random.rand(50)
y = np.arange(len(x))

# Plot data:
fig, ax = plt.subplots(figsize=(11, 4))
fillA = ax.fill_between(y, x-0.25, 0.5, color='darkolivegreen', alpha=0.65, lw=0)
fillB = ax.fill_between(y, x, 0.5, color='indianred', alpha=0.75, lw=0)

linec, = ax.plot(y, np.zeros(len(y))+0.5, color='blue', lw=1.5)
linea, = ax.plot(y, x, color='orange', lw=1.5)
lineb, = ax.plot(y, x-0.25, color='black', lw=1.5)

# Define an arbitrary legend handle with a proxy:
rec1 = plt.Rectangle((0, 0), 1, 1, fc='blue', lw=0, alpha=0.25)

# Generate the legend:
handles = [linea, lineb, linec, fillA, fillB, (fillA, fillB),
           rec1, (fillA, fillB, rec1)]
labels = ['a', 'b', 'c', 'A', 'B', 'A+B', 'C', 'A+B+C']
ax.legend(handles, labels, loc=2, ncol=4)

ax.axis(ymin=-1, ymax=2)

plt.show()

enter image description here

+2

, ian_itor, tacaswell Jean-Sébastien, , , , , .

handles, labels = ax.get_legend_handles_labels()
display = (0,1,2,3,4)

overlap_1 = plt.Line2D((0,1),(0,0), color='firebrick', linestyle='-',linewidth=15, alpha = 0.85)
overlap_2= plt.Line2D((0,1),(0,0), color='darkolivegreen',linestyle='-',linewidth=15, alpha = 0.65)
over_lo_3= plt.Line2D((0,1),(0,0), color='indianred',linestyle='-',linewidth=15, alpha = 0.75) 

ax.legend([handle for i,handle in enumerate(handles) if i in display]+[overlap_1 , overlap_2 , overlap_3 ],
      [label for i,label in enumerate(labels) if i in display]+['D','F','G'])

enter image description here

+1

Source: https://habr.com/ru/post/1657745/


All Articles