Seaborn Swarmplot 轴间隔格式

Seaborn Swarmplot Axis Interval Formatting

目前,我的 seaborn swarm plot 的 x 轴间隔太近导致了一个看起来像这样的图:image 下面是我当前的代码在哪里。玩具数据 x 值 (32, 34, 76, 34, 64, 34, 23, 76, 34, 63, 75, 34, 76, 34, 34, 45, 56, 67, 34, 56) Y 值 ( 0,0,1,0,1,1,0,1,0,1,0,1,1,0,0,0,1,0,1,0)

sns.swarmplot(x="age", y="sex", hue="target", palette=["green", "red"], data=df)

有没有办法格式化间隔?例如,我希望 x 轴总共有 5 个标签。当我使用 relplot 绘图时,轴标签看起来不错,但当我切换到 swarmplot 时它就搞砸了。我似乎无法在任何地方找到这方面的信息。我发现的所有其他问题似乎都不适用于 swarmplots。

这个 post here (post) 与我的问题非常相似,但是我没有使用 plt 而是使用 seaborn。非常感谢任何帮助。

您可以通过 ax = sns.swarmplot(...) 访问所有 matplotlib 功能,然后调用例如ax.get_xticks().

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

N = 100
df = pd.DataFrame({'x': np.random.randint(30, 80, N, dtype=int),
                   'y': np.random.randint(0, 2, N),
                   'target': np.random.randint(0, 2, N)})
ax = sns.swarmplot(x='x', y='y', hue="target", palette=["green", "red"], data=df)
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
ax.set_xticks(ticks[4::5])
ax.set_xticklabels(labels[4::5])
ax.set_yticks([0, 1])
plt.show()