1

I've made this boxplot graph

# Tamanho do gráfico em polegadas
plt.figure(figsize=(11, 6))

# Gráfico
ax = sns.boxplot(x="CÓD. ESTAÇÃO", y ="FERRO", data=df_FERRO, linewidth=1.0, color='#5d6b75')

ax.set_ylim(min(df_FERRO['FERRO']) - 0.5, max(df_FERRO['FERRO']) + 0.5)

# Cores
colors = ['#8ECEEA', '#FDF7AD', '#AC5079']
bins = [0.3, 5, 20]
base = -10
for top, c in zip(bins, colors):
    ax.axhspan(base, top, color=c, zorder=0)
    base = top
# Adicionando Título ao gráfico
plt.title("Ferro dissolvido (2017 - 2022)", loc="center", fontsize=18)
plt.xlabel("Estação")
plt.ylabel("mg/L Fe")

plt.show()

boxplot

I need to insert a legend for the layers (represented by colors), i may say it's a legend for the "colored boxes". I've got this example (graph made in R) of what I expect: Legend needed circled in RED

It doesn't need to be exact like this graph, but it needs to express this idea. I've only found examples for lines, instead of layers.

1
  • 1
    You need to add a label= to ax.axhspan(base, top, color=c, zorder=0, label=f'bin={base}-{top}'). Then these labels together with the colored boxes will appear in the legend, which you can create with plt.legend(loc='upper left', title='legenda').
    – JohanC
    Commented Feb 28 at 20:55

1 Answer 1

1

To get a legend in matplotlib, you typically add a label= keyword to the elements you want to pop up in the legend. Then, calling ax.legend() will add a legend with these elements together with the label text. The legend will appear in the same order as the elements are created in the plot. To have the highest label at the top in the legend, the code can be changed to draw that one first.

Here is an example:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

# create some random test data
np.random.seed(777)
df_FERRO = pd.DataFrame({"CÓD. ESTAÇÃO": np.random.randint(1000, 1011, 100),
                         "FERRO": np.random.uniform(0.3, 5, 100)})

plt.figure(figsize=(11, 6))

ax = sns.boxplot(x="CÓD. ESTAÇÃO", y="FERRO", data=df_FERRO, linewidth=1.0, color='#5d6b75')
ax.set_ylim(min(df_FERRO['FERRO']) - 0.5, max(df_FERRO['FERRO']) + 0.5)

colors = ['#AC5079', '#FDF7AD', '#8ECEEA']
labels = ["high", "normal", "low"]
bins = [20, 5, 0.3, -10]
for base, top, c, label in zip(bins[1:], bins[:-1], colors, labels):
    ax.axhspan(base, top, color=c, zorder=0, label=label)

leg = ax.legend(title='legenda', framealpha=0.9)
for h in leg.legend_handles:
    h.set_edgecolor('black')

# set title and axes labels
ax.set_title("Ferro dissolvido (2017 - 2022)", loc="center", fontsize=18)
ax.set_xlabel("Estação")
ax.set_ylabel("mg/L Fe")

plt.show()

legend for axhspan

Not the answer you're looking for? Browse other questions tagged or ask your own question.