python - 如何防止 sns.countplot 中的 x 轴标签重叠

标签 python pandas matplotlib seaborn

为了剧情

sns.countplot(x="HostRamSize",data=df)

我得到下图与 x 轴标签混合在一起,我该如何避免这种情况?我应该改变图表的大小来解决这个问题吗?

enter image description here

最佳答案

有一个像这样的系列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()

enter image description here

减小字体大小

ax = sns.countplot(x="Column", data=ds)

ax.set_xticklabels(ax.get_xticklabels(), fontsize=7)
plt.tight_layout()
plt.show()

enter image description here

当然,这些的任何组合都同样有效。

设置 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/

相关文章:

python - 如何使 Plotly 图形动画工作

python - pandas groupby 无法正确计数。为什么?

python - 如何通过傅里叶变换获得有关图像清晰度的信息?

python - Python 日志轮换的 RotatingFileHandler 和 logrotate.d + WatchedFileHandler 之间有区别吗?

python - 通过 basicConfig 和 RotatingFileHandler 使用日志记录

python - 值错误: time data '2018 May 23' does not match format '%Y%b%d' (match)

python - 使用二进制值重新采样 pandas 数据帧时出现问题

python - Matplotlib 显示页面上的滚动条

python - 外线 Seaborn fiddle 图/箱线图

python - 如何从命令行调用文件中的特定 python 函数?