如何防止sns.countplot中的x轴标签重叠 [英] How to prevent overlapping x-axis labels in sns.countplot

查看:633
本文介绍了如何防止sns.countplot中的x轴标签重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于情节

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

我得到了下图,其中x轴标签混合在一起,如何避免这种情况?我应该更改图形的大小来解决此问题吗?

I got the following graph with x-axis label mixing together, how do I avoid this? Should I change the size of the graph to solve this problem?

推荐答案

具有这样的系列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})

有一些选项可以使轴标签更具可读性.

there are several options to make the axis labels more readable.

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()

当然,这些方法的任何组合都将同样有效.

Of course any combination of those would work equally well.

可以使用 rcParams

plt.rcParams["figure.figsize"] = (8, 4)
plt.rcParams["xtick.labelsize"] = 7

将其放在juypter笔记本上可能会很有用,以使这些设置适用于其中生成的任何图形.不幸的是,使用rcParams不能旋转xticklabels.

This might be useful to put on top of a juypter notebook such that those settings apply for any figure generated within. Unfortunately rotating the xticklabels is not possible using rcParams.

我想值得注意的是,同样的策略自然也适用于seaborn barplot,matplotlib bar图或pandas.bar.

I guess it's worth noting that the same strategies would naturally also apply for seaborn barplot, matplotlib bar plot or pandas.bar.

这篇关于如何防止sns.countplot中的x轴标签重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆