我不确定为什么 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()
这也适用于 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()
factorplot
用于主要独立变量为分类变量的情况,并已更名为catplot
。
factorplot
。catplot
。relplot
和kind='scatter'
。
字符串
而不是日期时间
或数值
,则会显示所有的xticks。import seaborn as sns
titanic = sns.load_dataset('titanic')
g = sns.relplot(x='age', y='fare', hue='survived', col='sex', data=titanic)
没有使用`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()
FormatStrFormatter('%d')
是如何工作的?更具体地说,%d
是如何工作的,是否有其他替代方法? - Ali AsgariFormatStrFormatter
实例以供set_major_formatter
使用。%d
来自此处的格式规范迷你语言:https://docs.python.org/3/library/string.html#formatspec。我不知道是否有任何替代方案。 - mechanical_meatfactorplot
(现在是catplot
)用于分类自变量。 - Trenton McKinney