gpt4 book ai didi

Seaborn despine() 带回 ytick 标签

转载 作者:行者123 更新时间:2023-12-02 16:09:41 29 4
gpt4 key购买 nike

这是一个代码片段

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time')
g = g.map(plt.hist, "tip")

输出如下

enter image description here

我想在这些图中引入 despine offset,同时保持其余部分不变。因此,我在现有代码中插入了despine函数:

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time')
g.despine(offset=10)
g = g.map(plt.hist, "tip")

结果如下图

enter image description here

因此,偏移量将应用于轴。然而,右图上的ytick标签又回来了,这是我不想要的。

有人可以帮我解决这个问题吗?

最佳答案

要删除 yaxis 刻度标签,您可以使用以下代码:

库:

import seaborn as sns
sns.set_style('ticks')

调整后的代码:

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time')
g.despine(offset=10)
g = g.map(plt.hist, "tip")

# IMPORTANT: I assume that you use colwrap=None in FacetGrid constructor
# loop over the non-left axes:
for ax in g.axes[:, 1:].flat:
# get the yticklabels from the axis and set visibility to False
for label in ax.get_yticklabels():
label.set_visible(False)
ax.yaxis.offsetText.set_visible(False)

enter image description here

更一般一点,想象一下,您现在有一个 2x2 FacetGrid,您想要使用偏移量进行缩放,但 x- 和 yticklabels 返回:

enter image description here

使用以下代码将它们全部删除:

tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time', row='sex')
g.despine(offset=10)
g = g.map(plt.hist, "tip")

# IMPORTANT: I assume that you use colwrap=None in FacetGrid constructor
# loop over the non-left axes:
for ax in g.axes[:, 1:].flat:
# get the yticklabels from the axis and set visibility to False
for label in ax.get_yticklabels():
label.set_visible(False)
ax.yaxis.offsetText.set_visible(False)

# loop over the top axes:
for ax in g.axes[:-1, :].flat:
# get the xticklabels from the axis and set visibility to False
for label in ax.get_xticklabels():
label.set_visible(False)
ax.xaxis.offsetText.set_visible(False)

enter image description here

更新:

为了完整起见,mwaskom ( ref to github issue ) 解释了为什么会出现此问题:

So this happens because matplotlib calls axis.reset_ticks() internally when moving the spine. Otherwise, the spine gets moved but the ticks stay in the same place. It's not configurable in matplotlib and, even if it were, I don't know if there is a public API for moving individual ticks. Unfortunately I think you'll have to remove the tick labels yourself after offsetting the spines.

关于Seaborn despine() 带回 ytick 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37860163/

29 4 0