1 year ago

#378529

test-img

Banarnia

Marker not showing in legend after changing labels (seaborn and matplotlib)

When I change the legend titles, only the first of my two markers is redrawn, am I doing something wrong, or is there a workaround?

I ran the code below:

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

#create dataframe
np.random.seed(seed=10)

x = np.arange(0,20)
y1 = np.arange(0,20) + 10*np.random.rand(20)
y2 = np.arange(20,0,-1) + 10*np.random.rand(20)
mask = np.random.randint(low=0, high=2, size=20, dtype=bool)

df = pd.DataFrame()

df['x'] = x
df['y1'] = y1
df['y2'] = y2
df['mask'] = mask

#plot results
fig, axs = plt.subplots(2)

f1 = sns.scatterplot(data=df, y='y1', x='x', ax=axs[0], hue="mask")
f2 = sns.scatterplot(data=df, y='y2', x='x', ax=axs[1], hue="mask")

new_title = ""
new_labels = ['Include', 'Exclude']

for ax in axs:
    ax.legend(title=new_title, labels=new_labels)
    
fig.savefig(r"C:\\Temp\error.png", bbox="tight")

The result is below. As you can see the "Include" label in the legend has a marker, but the "Exclude" label does not

enter image description here

python

matplotlib

seaborn

legend

0 Answers

Your Answer

Accepted video resources