Python 如何防止在 sns.countplot 中重叠 x 轴标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42528921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to prevent overlapping x-axis labels in sns.countplot
提问by william007
回答by ImportanceOfBeingErnest
Having a Series ds
like this
有一系列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.
有几个选项可以使轴标签更具可读性。
Change figure size
更改图形大小
plt.figure(figsize=(8,4)) # this creates a figure 8 inch wide, 4 inch high
sns.countplot(x="Column", data=ds)
plt.show()
Rotate the ticklabels
旋转刻度标签
ax = sns.countplot(x="Column", data=ds)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
plt.tight_layout()
plt.show()
Decrease Fontsize
减小字体大小
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.
当然,这些的任何组合都会同样有效。
Setting rcParams
设置rcParams
The figure size and the xlabel fontsize can be set globally using rcParams
可以使用rcParams全局设置图形大小和 xlabel 字体大小
plt.rcParams["figure.figsize"] = (8, 4)
plt.rcParams["xtick.labelsize"] = 7
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.
这对于放置在 juypter notebook 顶部可能很有用,以便这些设置适用于其中生成的任何图形。不幸的是,使用 rcParams 无法旋转 xticklabels。
I guess it's worth noting that the same strategies would naturally also apply for seaborn barplot, matplotlib bar plot or pandas.bar.
我想值得注意的是,同样的策略自然也适用于 seaborn barplot、matplotlib bar plot 或 pandas.bar。
回答by hui chen
If you just want to make sure xticks labels are not squeezed together, you can set a proper fig size and try fig.autofmt_xdate()
.
如果您只是想确保 xticks 标签不会挤在一起,您可以设置适当的 fig 大小并尝试fig.autofmt_xdate()
.
This function will automatically align and rotate the labels.
此功能将自动对齐和旋转标签。
回答by Genius
You can rotate the x_labels
and increase their font size using the xticks
methods of pandas.pyplot
.
您可以x_labels
使用 的xticks
方法旋转和增加它们的字体大小pandas.pyplot
。
For Example:
例如:
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'
)
For more such modifications you can refer this link: Drawing from Data
有关更多此类修改,您可以参考此链接: 从数据中绘制