Seaborn:设置 catplot 条的厚度
Seaborn: Set thickness of catplot bars
我想增加 catplot 中条形的粗细并制作 y 轴日志。可重现的例子:
import seaborn as sns
df = sns.load_dataset("titanic")
p = sns.catplot(x="alive", hue="alive", col="deck",
data=df, kind="count",
col_wrap = 4 )
plt.legend(title = 'alive',bbox_to_anchor=(1.05, 1),
loc=2, borderaxespad=0.)
如果您同时使用 x
和 hue
两个可能的值,seaborn 将为每个子图腾出 4 个条:no-no、no-yes、yes-no、yes-yes。在这种情况下,其中两个将是空的。解决方案是不要显式设置 hue
.
然后,您可以从 xticklabels 和 xlabel 作为标题创建图例。在网格中,xticks 通常只显示在最后一行,因此我们可以使用最后一个子图作为标签。
因为现在信息在图例中,所以可以删除 xticks 和 xlabel。
示例如下:
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset("titanic")
p = sns.catplot(x="alive", col="deck",
data=df, kind="count",
col_wrap=4)
# create legend from the patches (for the colors) and xticklabels (for the text)
plt.legend(p.axes[0].patches,
[l.get_text() for l in p.axes[-1].get_xticklabels()],
title=p.axes[-1].get_xlabel(),
bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
# remove xticks because they now are in the legend
for ax in p.axes:
ax.set_xticks([])
ax.set_xlabel('')
plt.show()
我想增加 catplot 中条形的粗细并制作 y 轴日志。可重现的例子:
import seaborn as sns
df = sns.load_dataset("titanic")
p = sns.catplot(x="alive", hue="alive", col="deck",
data=df, kind="count",
col_wrap = 4 )
plt.legend(title = 'alive',bbox_to_anchor=(1.05, 1),
loc=2, borderaxespad=0.)
如果您同时使用 x
和 hue
两个可能的值,seaborn 将为每个子图腾出 4 个条:no-no、no-yes、yes-no、yes-yes。在这种情况下,其中两个将是空的。解决方案是不要显式设置 hue
.
然后,您可以从 xticklabels 和 xlabel 作为标题创建图例。在网格中,xticks 通常只显示在最后一行,因此我们可以使用最后一个子图作为标签。
因为现在信息在图例中,所以可以删除 xticks 和 xlabel。
示例如下:
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset("titanic")
p = sns.catplot(x="alive", col="deck",
data=df, kind="count",
col_wrap=4)
# create legend from the patches (for the colors) and xticklabels (for the text)
plt.legend(p.axes[0].patches,
[l.get_text() for l in p.axes[-1].get_xticklabels()],
title=p.axes[-1].get_xlabel(),
bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
# remove xticks because they now are in the legend
for ax in p.axes:
ax.set_xticks([])
ax.set_xlabel('')
plt.show()