Skip to content

Not clear how to reposition seaborn.histplot legend #2280

@mortonjt

Description

@mortonjt

I was pretty excited about seeing the histplot functionality coming out, and I'm getting beautiful figures with it already.

I'm trying to finetune my figures and reposition the legends - but am running into issues when moving the legend.
Below is toy example

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots()
x = np.hstack((np.random.normal(0, 1, 100), np.random.normal(-0.5, 1, 100), np.random.normal(0.5, 1, 100)))
data = pd.DataFrame({'x': x, 'd' : ['a'] * 100 + ['b'] * 100 + ['c'] * 100})
g = sns.histplot(data, x='x', hue="d", element="step", stat="probability", ax=ax)

image

When I move the legend to the upper left, the legend disappears with the warning No handles with labels found to put in legend..

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots()
x = np.hstack((np.random.normal(0, 1, 100), np.random.normal(-0.5, 1, 100), np.random.normal(0.5, 1, 100)))
data = pd.DataFrame({'x': x, 'd' : ['a'] * 100 + ['b'] * 100 + ['c'] * 100})
g = sns.histplot(data, x='x', hue="d", element="step", stat="probability", ax=ax, legend=False)
ax.legend(loc='upper-left')

image

This is interesting, because it doesn't appear to be an issue with the other plots
https://stackoverflow.com/questions/27019079/move-seaborn-plot-legend-to-a-different-position
https://stackoverflow.com/questions/53733755/how-to-move-legend-to-outside-of-a-seaborn-scatterplot/53737271

I'm curious if this is unique to histplot (or if I'm overlooking something).

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions