2017-02-26 50 views
2

我使用matplotlib程序包在Jupyter Notebook中繪製圖表。 這裏是我的代碼片段:使用%matplotlib筆記本時省略並縮進圖表

%matplotlib notebook 
import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 

plt.figure(figsize=(40,8)) 

freq_series = pd.Series.from_array(count_axis) 
ax = freq_series.plot(kind='bar') 
ax.set_xlabel("Tags") 
ax.set_ylabel("Count") 

plt.bar(range(len(count_axis)), count_axis, align='center') 
plt.xticks(range(len(name_axis)), name_axis, size=16, rotation=90) 

rects = ax.patches 

for rect, count in zip(rects, count_axis): 
    height = rect.get_height() 
    ax.text(rect.get_x() + rect.get_width()/2, height + 5, count, ha='center', va='bottom') 

plt.show() 

如果X軸的標籤文字太長,它就會被省略/剖這樣也,圖形對默認怪異左縮進:

enter image description here

我該如何解決這個問題? (因爲使用%matplotlib notebook而縮放)。 當我使用%matplotlib inline X軸不會被省略,並且沒有縮進,但我無法縮放圖形,我需要此功能。

編輯:好了,縮進是因爲線plt.figure(figsize=(40,8))在那裏我靜態設置寬度爲40。但我仍然不知道如何擺脫x軸遺漏的。

+1

您可以在調用'plt.show()'之前調用'plt.tight_layout()',這些問題將得到解決。 (至少他們是給我的)。可能還有其他方法可以解決這個問題(使用'gridspec'這樣的東西),但這些對於這個例子來說都是過分的。 – Elliot

+0

不錯!我認爲你不能發佈這個aswer。謝謝。 – delusionX

回答

2

使用最基本的佈局,tight_layout將把所有東西都放到頁面上。當我在jupyter notebook中試過時,奇怪的縮進也被刪除了。

plt.tight_layout() 
plt.show() 
相關問題