Home > other >  Matplotlib scatterplot subplot legends overwrite one another
Matplotlib scatterplot subplot legends overwrite one another

Time:01-31

I have a scatterplot figure with subplots generated using a for loop. Within the figure, I am trying to create a single legend but each time a subplot and legend is rendered the legend is overwritten by the next subplot, so the figure that is generated contains a single legend pertaining only to the last subplot. I would like the legend to pertain to all subplots (i.e., it should include years 2019, 2020, 2021 and 2022). Here is my code, please let me know how I can tweak it.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches

df = pd.read_excel(path)

spp = df.SPP.unique()

fig, axs = plt.subplots(nrows=8, ncols=4, figsize=(14, 14))

for spp_i, ax in zip(spp, axs.flat):
    df_1 = df[df['SPP'] == spp_i]
    labels = list(df_1.Year.unique())
    x = df_1['Length_mm']
    y = df_1['Weight_g']
    levels, categories = pd.factorize(df_1['Year'])
    colors = [plt.cm.tab10(i) for i in levels]
    handles = [matplotlib.patches.Patch(color=plt.cm.tab10(i), label=c) for i, c in enumerate(categories)]
    ax.scatter(x, y, c=colors)
    plt.legend(handles=handles)

plt.savefig('Test.png', bbox_inches='tight', pad_inches=0.1, dpi=600)

Here is figure, as you can see the legend in the bottom right is for the last subplot only.
sns.relplot example

  • Related