Я смог сделать это для sns.barplot, но те же строки кода, похоже, не работают с sns.histplot (а эти данные необходимо отображать с помощью sns.histplot).
У меня есть фиктивный код ниже, с которым можно повозиться. Я закомментировал строки, которые я
Код: Выделить всё
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Create a dummy DataFrame with random data
crops = [
"apple",
"banana",
"orange",
"potato",
"zucchini",
"kale",
"strawberry",
"raspberry",
"turnip",
"onion",
]
farms = [
"n",
"s",
"e",
"w",
]
np.random.seed(42)
n_samples = 100
counts = np.random.randint(1, 200, size=n_samples)
choices = np.random.choice(crops, size=n_samples)
locations = np.random.choice(farms, size=n_samples)
df = pd.DataFrame({"counts": counts, "crops": choices, "farms": locations})
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
h = [] # Initialize an empty list to collect handles
l = [] # Initialize an empty list to collect labels
rowindex = [0, 0, 1, 1]
colindex = [0, 1, 0, 1]
selection = ["farms == 'n'", "farms == 's'", "farms == 'e'", "farms == 'w'"]
for row, col, sele in zip(rowindex, colindex, selection):
g = sns.histplot(
data=df.query(sele),
x="counts",
kde=True,
stat="count",
hue="crops", # Add the hue parameter
ax=axes[row, col],
)
handles, labels = g.get_legend_handles_labels()
h.extend(handles)
l.extend(labels)
axes[row, col].get_legend().remove() # Remove individual legends from subplots
# Create a single legend for the entire figure
by_label = dict(zip(l, h))
g.legend(by_label.values(), by_label.keys(), bbox_to_anchor=(0.9,0.65), loc='upper right')
plt.show()
Код: Выделить всё
handles, labels = g.get_legend_handles_labels()
h.extend(handles)
l.extend(labels)
axes[row, col].get_legend().remove() # Remove individual legends from subplots
# Create a single legend for the entire figure
by_label = dict(zip(l, h))
g.legend(by_label.values(), by_label.keys(), bbox_to_anchor=(0.9,0.65), loc='upper right')
[img]https://i .sstatic.net/IqKXMNWk.png[/img]
С этими строками в коде у меня нет легенд:

В идеале у меня должна быть одна легенда (вне сюжета) со всеми «культуры» перечислены один раз (порядок не важен). Кто-нибудь знает, что я делаю не так?
Как уже упоминалось, это РАБОТАЕТ с sns.barplot. Если вы измените бит g = на это:
Код: Выделить всё
g = sns.barplot(
data=df.query(sele),
x="counts",
y="counts",
hue="crops", # Add the hue parameter
ax=axes[row, col],
)

Подробнее здесь: https://stackoverflow.com/questions/787 ... plicate-la