web-dev-qa-db-ja.com

sns.countplotでx軸ラベルが重複しないようにする方法

プロット用

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

X軸ラベルが混在した次のグラフが表示されましたが、これを回避するにはどうすればよいですか?この問題を解決するには、グラフのサイズを変更する必要がありますか?

enter image description here

24
william007

このようなシリーズ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の設定

Figureサイズとxlabelフォントサイズは、 rcParams を使用してグローバルに設定できます

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

これは、これらの設定が内部で生成される図に適用されるように、juypterノートブックの上に置くと便利です。残念ながら、rcParamsを使用してxticklabelsを回転させることはできません。

同じ戦略が当然、海生まれの棒グラフ、matplotlib棒グラフ、またはpandas.barにも適用されることに注意する価値があると思います。

Xticksラベルが一緒に圧縮されないようにしたい場合は、適切なfigサイズを設定してfig.autofmt_xdate()を試してください。

この関数は、ラベルを自動的に整列および回転します。

4
hui chen