我正在嘗試創建一系列直方圖(來自 a pd.DataFrame)。我想fare在不同的行和不同的類(class在下面的示例中)在不同的列中使用不同的數量(在下面的示例中),如下所示:
import seaborn as sns
from matplotlib import pyplot as plt
titanic = sns.load_dataset("titanic")
df = pd.melt(titanic, id_vars=["sex", "class"], value_vars=["fare", "age"])
sns.displot(
data=df,
x="value",
row="variable",
col="class",
hue="sex",
facet_kws={"sharex": "row", "sharey": "row"},
)
plt.show()

不幸的是,由于common_bins=True引數的原因,軸似乎在行和列之間共享,我不想要這種情況,因為不同的行具有不同的數量,這些數量可能在非常不同的范圍內。使用common_bins=False我得到以下資訊:
import seaborn as sns
from matplotlib import pyplot as plt
titanic = sns.load_dataset("titanic")
df = pd.melt(titanic, id_vars=["sex", "class"], value_vars=["fare", "age"])
sns.displot(
data=df,
x="value",
row="variable",
col="class",
hue="sex",
facet_kws={"sharex": "row", "sharey": "row"},
common_bins=False,
)
plt.show()

在這種情況下,軸僅在我想要的同一行中共享(這更適合表示具有不同范圍的數量),但不再共享 bin。我希望在列之間共享垃圾箱,或者至少在同一個直方圖中(但最好跨列共享)。
I also tried to use sns.FacetGrid directly, but in such case it does not seem possible to get a legend 
Is there a simple way to share bins and axis on the same row and get a legend based on hue? Essentially the last figure but with the legend of the first two figures (and possibly bins shared across the same row).
uj5u.com熱心網友回復:
FacetGrid旨在在每個方面顯示相同的 x/y 關系。如果這不是您想要做的,那么使用更程式化的方法可能會取得更大的成功。這是我們FacetGrid用來設定圖形但單獨回圈軸的一種想法。
titanic = sns.load_dataset("titanic")
df = pd.melt(titanic, id_vars=["sex", "class"], value_vars=["fare", "age"])
binwidths = {"fare": 20, "age": 5}
g = sns.FacetGrid(df, col="class", row="variable", sharex="row", sharey="row", height=2.5)
for (var, cls), ax in g.axes_dict.items():
sns.histplot(
data=titanic[titanic["class"] == cls],
x=var, hue="sex",
binwidth=binwidths[var],
ax=ax, legend=ax is g.axes.flat[-1])
g.set_titles(template="{col_name} {col_var}")
plt.setp(g.axes[1], title="")
sns.move_legend(ax, loc="lower left", bbox_to_anchor=(1, 1))

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/376211.html
標籤:python matplotlib seaborn data-visualization
