2017-06-02 535 views
4

我想在Jupyter筆記本中製作具有指定大小,標題和圖例位置的堆疊水平條形圖。當我使用其他堆棧溢出解決方案時,我會打印出幾張圖形而不是一張。這裏有一個簡化的例子:在Jupyter筆記本中給出多個圖表的python中的水平堆疊條形圖

import pandas as pd 
import matplotlib.pyplot as plt 
a = [3,5,4,2,1] 
b = [3,4,5,2,1] 
c = [3,5,4,6,1] 
df = pd.DataFrame({'a' : a,'b' : b, 'c' : c}) 
df.plot.barh(stacked=True); 

fig, ax = plt.subplots() 
fig.set_size_inches(6,6) 

ax.set_title("My ax title") 
#plt.title("My plt title") # This seems to be identical to ax.set_title 
# Which is prefered? 
ax.legend(loc='upper left') 

plt.show() 

這段代碼給了我下面兩個圖。情節是我正在尋找的,但我的尺寸和傳說位置被忽略,標題被放在第二張圖上,我不想要。

enter image description hereenter image description here

注:我使用plot.barh從熊貓,因爲我得到了它的工作,但我會同樣樂於直接從matplotlib做到這一點。

回答

4

您可以將返回對象從plot分配給變量ax。然後做你想做的事。

a = [3,5,4,2,1] 
b = [3,4,5,2,1] 
c = [3,5,4,6,1] 
df = pd.DataFrame({'a' : a,'b' : b, 'c' : c}) 
ax = df.plot.barh(stacked=True); 

ax.figure.set_size_inches(6,6) 

ax.set_title("My ax title") 
ax.legend(loc='upper left') 

enter image description here


或者,你可能會引用您在plot調用創建ax

a = [3,5,4,2,1] 
b = [3,4,5,2,1] 
c = [3,5,4,6,1] 
df = pd.DataFrame({'a' : a,'b' : b, 'c' : c}) 

fig, ax = plt.subplots() 
fig.set_size_inches(6,6) 

df.plot.barh(stacked=True, ax=ax); 

ax.set_title("My ax title") 
ax.legend(loc='upper left') 

enter image description here

2

你正在創建使用

df.plot.barh(stacked=True) 

再說你正在創建使用

fig, ax = plt.subplots() 

擺脫一個空的陰謀情節,這將需要第二個空情節護理

你可以通過裏面的參數像

df.plot.barh(stacked=True,title = "My ax title", figsize = (6,6)) 
+1

這是完全正確的。 – piRSquared