如何在sns.countplot中防止x轴标签重叠

68

关于情节

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

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

enter image description here


1
这个问题很差,原始数据在哪里?有重新创建数据框的代码吗? - EdChum
也许这个有帮助?! - Cleb
可能是如何更改seaborn图的图像大小?的重复问题。 - Paul H
此问题针对轴级别函数(具有 ax= 参数的函数),而非图形级别函数。请参见图形级别与轴级别函数。有关图形级别绘图,请参见如何在 seaborn catplot 中旋转 xticklabels - Trenton McKinney
5个回答

105

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

将其放在Jupyter笔记本的顶部可能很有用,以便这些设置适用于生成的任何图形。不幸的是,使用rcParams无法旋转xticklabels。

我想值得注意的是,相同的策略自然也适用于seaborn条形图、matplotlib条形图或pandas.bar。


尝试旋转刻度标签时出现“AttributeError:'FacetGrid'对象没有属性'get_xticklabels'”。 - PlsWork
@AnnaVopureta 我并没有声称这适用于 FacetGrid。它适用于任何返回轴的 seaborn 函数。 - ImportanceOfBeingErnest
当我使用以下的seaborn函数并返回一个轴时,它 failed 了: ax = sns.catplot(y="Dataset", x="Size (bytes)", hue="Implementation", data=pdData, height=6, kind="bar", palette="muted", legend=False) - PlsWork
1
我知道。因为catplot返回的是FacetGrid,而不是axes。 - ImportanceOfBeingErnest
我之前不知道,我的错。如何解决catplot(和其他返回FacetGrid的函数)的重叠轴标签问题? - PlsWork
这里有一种方法可以实现:for axes in ax.axes.flat: axes.set_xticklabels(axes.get_xticklabels(), rotation=65, horizontalalignment='right') 解决方案在此处描述:https://www.drawingfromdata.com/how-to-rotate-axis-labels-in-seaborn-and-matplotlib - PlsWork

14
你可以使用 pandas.pyplot 的 xticks 方法,旋转 x 标签并增加它们的字体大小。
例如:
import matplotlib.pyplot as plt
plt.figure(figsize=(10,5))
chart = sns.countplot(x="HostRamSize",data=df)

plt.xticks(
    rotation=45, 
    horizontalalignment='right',
    fontweight='light',
    fontsize='x-large'  
)

您可以参考此链接以获得更多类似的修改: Drawing from Data


1
你真是个天才!这是我见过的最好的答案,它不依赖于ax.set_xticklabels(ax.get_xticklabels(), fontsize=7)方法。谢谢! - shadow_dev

10
如果您只想确保x轴标签不会挤在一起,您可以设置一个合适的图形大小并尝试使用 fig.autofmt_xdate()。此函数将自动对齐和旋转标签。

5

我不知道对你来说是否可行,但是可能将图形旋转可能是一种解决方案(而不是在 x= 上绘制,在 y= 上绘制),这样:

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

enter image description here


3
plt.figure(figsize=(15,10)) #adjust the size of plot
ax=sns.countplot(x=df['Location'],data=df,hue='label',palette='mako')

ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")  #it will rotate text on x axis

plt.tight_layout()
plt.show()

你可以尝试这段代码,并根据你的需求更改大小和旋转。


请不要发布仅包含代码的答案。对于未来的读者来说,更有趣的是看到为什么这个答案回答了问题。而且带有解释的答案往往更容易被接受。 - Akif

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