2017-10-18 240 views
-2

我的x軸標記標記(圖下方的標記)正在竊取整個圖中的寶貴空間。我試圖通過改變文本旋轉來縮小它的大小,但是這並沒有什麼幫助,因爲文本標籤很長。減少matplotlib圖中的xticklabels區域

是否有更好的方法來減少xticklabel區域佔用的空間?例如,我可以在酒吧內顯示這些文字嗎?感謝您的支持。

我對圖形設置的代碼是:

import matplotlib.pyplot as plt 
import matplotlib 
matplotlib.rcParams['font.sans-serif'] = "Century Gothic" 
matplotlib.rcParams['font.family'] = "Century Gothic" 

ax = df1.plot.bar(x = '', y = ['Events Today', 'Avg. Events Last 30 Days'], rot = 25, width=0.8 , linewidth=1, color=['midnightblue','darkorange']) 

for item in ([ax.xaxis.label, ax.yaxis.label] + 
     ax.get_xticklabels() + ax.get_yticklabels()): 
    item.set_fontsize(15) 

ax.legend(fontsize = 'x-large', loc='best') 
plt.tight_layout() 
ax.yaxis.grid(True, which='major', linestyle='-', linewidth=0.15) 
ax.set_facecolor('#f2f2f2') 
plt.show() 

enter image description here

+0

什麼有關[MCVE]這個問題的? – ImportanceOfBeingErnest

+0

?!提供描述,代碼,打印...... – Gonzalo

+1

你問我或者誰會傾向於回答這個問題,自己生成一些'df1'。這不是很好,因爲你是這裏尋求幫助的人。 – ImportanceOfBeingErnest

回答

1

當我結束了unaesthetically長xticklabels,我做的第一和最重要的是要儘量縮短他們。這似乎很明顯,但值得指出的是,使用縮寫或不同描述通常是最簡單和最有效的解決方案。

如果您遇到長名稱和某種字體大小的問題,我建議您製作一個水平條形圖。我通常更喜歡使用較長標籤的橫向繪圖,因爲它更容易閱讀未旋轉的文本(這也可能使字體大小進一步縮小)添加換行符也可以提供幫助。

這裏是一個與笨重的標籤的圖形示例:

import pandas as pd 
import seaborn as sns # to get example data easily 

iris = sns.load_dataset('iris') 
means = iris.groupby('species').mean() 
my_long_labels = ['looooooong_versicolor', 'looooooooog_setosa', 'looooooooong_virginica'] 
# Note the simpler approach of setting fontsize compared to your question 
ax = means.plot(kind='bar', y=['sepal_length', 'sepal_width'], fontsize=15, rot=25) 
ax.set_xlabel('') 
ax.set_xticklabels(my_long_labels) 

enter image description here

我將它更改爲水平barplot:

ax = means.plot(kind='barh', y=['sepal_length', 'sepal_width'], fontsize=15) 
ax.set_ylabel('') 
ax.set_yticklabels(my_long_labels) 

enter image description here

你可以在標籤中引入換行符以進一步改進已經可讀性:

ax = means.plot(kind='barh', y=['sepal_length', 'sepal_width'], fontsize=15, rot=0) 
ax.set_ylabel('') 
ax.set_yticklabels([label.replace('_', '\n') for label in my_long_labels]) 

enter image description here

這也適用於豎線:​​

ax = means.plot(kind='bar', y=['sepal_length', 'sepal_width'], fontsize=15, rot=0) 
ax.set_xlabel('') 
ax.set_xticklabels([label.replace('_', '\n') for label in my_long_labels]) 

enter image description here

最後,你也可以有酒吧內的文本,但是這是很難讀書。

ax = means.plot(kind='barh', y=['sepal_length', 'sepal_width'], fontsize=15) 
ax.set_ylabel('') 
ax.set_yticklabels(my_long_labels, x=0.03, ha='left', va='bottom') 

enter image description here

+0

令人驚歎!感謝這樣完整的答案! – Gonzalo