最佳答案
有一个像这样的系列ds
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(136)
l = "1234567890123"
categories = [ l[i:i+5]+" - "+l[i+1:i+6] for i in range(6)]
x = np.random.choice(categories, size=1000,
p=np.diff(np.array([0,0.7,2.8,6.5,8.5,9.3,10])/10.))
ds = pd.Series({"Column" : x})
有几个选项可以使轴标签更具可读性。
改变图形大小
plt.figure(figsize=(8,4)) # this creates a figure 8 inch wide, 4 inch high
sns.countplot(x="Column", data=ds)
plt.show()
旋转刻度标签
ax = sns.countplot(x="Column", data=ds)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
plt.tight_layout()
plt.show()
减小字体大小
ax = sns.countplot(x="Column", data=ds)
ax.set_xticklabels(ax.get_xticklabels(), fontsize=7)
plt.tight_layout()
plt.show()
当然,这些的任何组合都同样有效。
设置 rcParams
可以使用rcParams全局设置图形大小和xlabel字体大小
plt.rcParams["figure.figsize"] = (8, 4)
plt.rcParams["xtick.labelsize"] = 7
这可能有助于放在 juypter 笔记本上,以便这些设置适用于其中生成的任何图形。不幸的是,使用 rcParams 无法旋转 xticklabels。
我想值得注意的是,同样的策略自然也适用于 seaborn barplot、matplotlib bar plot 或 pandas.bar。
关于python - 如何防止 sns.countplot 中的 x 轴标签重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42528921/