2016-08-04 227 views
0

我正在嘗試使用matplotlib來繪製多索引圖。但是,我正在努力從先前回答的代碼中找到確切的代碼。任何人都可以幫助我如何生成類似的圖表。使用Matplotlib進行多索引繪圖

enter image description here

import pandas as pd 
import matplotlib.pyplot as plt 
import pylab as pl 
import numpy as np 
import pandas 

xls_filename = "abc.xlsx" 
f = pandas.ExcelFile(xls_filename) 
df = f.parse("Sheet1", index_col='Year' and 'Month') 
f.close() 

matplotlib.rcParams.update({'font.size': 18}) # Font size of x and y-axis 
df.plot(kind= 'bar', alpha=0.70) 

它不是索引,因爲我想和沒有產生預期以及圖形。幫助讚賞。

回答

1

我創建了一個DataFrame中的一些值,我在你附加的圖上看到並繪製了它。

index = pd.MultiIndex.from_tuples(tuples=[(2011,), (2012,), (2016, 'M'), (2016, 'J')], names=['year', 'month']) 
df = pd.DataFrame(index=index, data={'1': [10, 140, 6, 9], '2': [23, 31, 4, 5], '3': [33, 23, 1, 1]}) 
df.plot(kind='bar') 

這就是結局

enter image description here

,其中數據幀是這樣

enter image description here

+0

嗨@維吾爾族居內伊,謝謝。任何想法如何從圖中消除NaN。我試過df [〜np.isnan(df)],其中df是當前數據幀。 – saltymisty73

+0

嗨! 'np.isnan(df)'或'df.isnan()'只檢查數據幀的值,而不檢查其索引。如果您通過'df.index.levels [1]'查看月份級別索引,您會發現在那裏沒有None。我猜那些NaNs只有在顯示df表時纔會出現。 我將單引號放在月份部分,而不是在創建元組時將它留空:tuples = [(2011,''),(2012,''),(2016,'M'),(2016,'J ')]'仍然不是一個很好的解決方案,但至少在劇情中你看不到「NaN」這個詞。 –

+0

嗯......這很有趣。我曾嘗試類似的方法來避免NaN,但仍然在圖上顯示括號。但是,你的方法給出了一個想法來產生一個像上面這樣的圖。 – saltymisty73