从 seaborn 绘图中删除一些 xtick 标签

13
在下面的截图中,所有我的x标签都重叠在一起了。
g = sns.factorplot(x='Age', y='PassengerId', hue='Survived', col='Sex', kind='strip', data=train);

我知道可以通过调用 g.set(xticks=[]) 来删除所有标签,但是是否有一种方法只显示一些年龄标签,例如0、20、40、60、80?

enter image description here

2个回答

22

我不确定为什么 X 轴上没有像 Y 轴一样合理的默认刻度和值。

FormatStrFormatter 实例是必需的,以提供 set_major_formatter%d 来自 格式规范迷你语言

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

titanic = sns.load_dataset('titanic')
sns.factorplot(x='age',y='fare',hue='survived',col='sex',data=titanic,kind='strip')
ax = plt.gca()
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))
ax.xaxis.set_major_locator(ticker.MultipleLocator(base=20))
plt.show()

enter image description here


这也适用于 catplot,它取代了 factorplot

titanic = sns.load_dataset('titanic')
sns.catplot(x='age', y='fare', hue='survived', col='sex', data=titanic, kind='strip')
ax = plt.gca()
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))
ax.xaxis.set_major_locator(ticker.MultipleLocator(base=20))
plt.show()

enter image description here


1
谢谢您的回答。您能否解释一下 FormatStrFormatter('%d') 是如何工作的?更具体地说,%d 是如何工作的,是否有其他替代方法? - Ali Asgari
@AliAsgari:必须提供FormatStrFormatter实例以供set_major_formatter使用。%d来自此处的格式规范迷你语言:https://docs.python.org/3/library/string.html#formatspec。我不知道是否有任何替代方案。 - mechanical_meat
1
我不确定为什么没有明智的默认刻度:因为 factorplot(现在是 catplot)用于分类自变量。 - Trenton McKinney

0
  • factorplot 用于主要独立变量为分类变量的情况,并已更名为catplot
  • 一般来说,接受的答案提供了一个解决方案来调整xticks的间距。
  • 主要问题是这应该是一个定量图,而不是一个分类图,这就是为什么每个类别都有一个xtick的原因。
  • 主要的要点是使用正确类型的图,即分类定量
    • 分类图将始终显示所有的xticks。
    • 定量图通常会格式化xticks的步长。
      • 如果用于x轴的值是字符串而不是日期时间数值,则会显示所有的xticks。
import seaborn as sns

titanic = sns.load_dataset('titanic')
g = sns.relplot(x='age', y='fare', hue='survived', col='sex', data=titanic)

enter image description here

没有使用`relplot`和`scatterplot`,这个图可以直接使用pandas.DataFrame.plot(或者ax.scatter)绘制,但这是一个更复杂的实现。
import seaborn as sns
import matplotlib.pyplot as plt

titanic = sns.load_dataset('titanic')

fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharex=True)

axes = axes.flat

for ax, (sex, data) in zip(axes, titanic.groupby('sex')[['survived', 'age', 'fare']]):
    ax.spines[['top', 'right']].set_visible(False)
    for (survived, sel), color in zip(data.groupby('survived'), ['tab:blue', 'tab:orange']):
        sel.plot(kind='scatter', x='age', y='fare', ec='w', s=30,
                 color=color, title=sex.title(), label=survived, ax=ax)
        
axes[0].get_legend().remove()
axes[1].legend(title='Survived', bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)
plt.show()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接