2016-05-13 134 views
0

鑑於以下數據幀:熊貓Matplotlib線圖

import pandas as pd 
import numpy as np 

df = pd.DataFrame(
     {'YYYYMM':[201603,201503,201403,201303,201603,201503,201403,201303], 
     'Count':[5,6,2,7,4,7,8,9], 
     'Group':['A','A','A','A','B','B','B','B']}) 
df 

    Count Group YYYYMM 
0 5   A  201603 
1 6   A  201503 
2 2   A  201403 
3 7   A  201303 
4 4   B  201603 
5 7   B  201503 
6 8   B  201403 
7 9   B  201303 

我需要生成每組的一行,在底部的彙總表的線圖。類似這樣的: enter image description here

我需要'YYYYMM'的每個實例像Pandas/Matplotlib一樣對待一年。 到目前爲止,這似乎幫助,但我不知道這是否會做的伎倆:

df['YYYYMM']=df['YYYYMM'].astype(str).str[:-2].astype(np.int64) 

然後,我這樣做是爲了透視數據:

t=df.pivot_table(df,index=['YYYYMM'],columns=['Group'],aggfunc=np.sum) 

    Count 
Group A B 
YYYYMM  
2013 7 9 
2014 2 8 
2015 6 7 
2016 5 4 

然後,我試過繪製它:

import matplotlib.pyplot as plt 
%matplotlib inline 
fig, ax = plt.subplots(1,1) 
t.plot(table=t,ax=ax) 

...這發生了:

enter image description here

我想做到以下幾點:

  1. remove從表底部

  2. 所有行(邊框)刪除表中

  3. 去除冗雜的文本x軸刻度標籤(它應該只顯示刻度標籤的年份)

我可以自己清理剩下的部分(刪除圖例和邊框等)。

提前致謝!

回答

2

由於您在參考中顯示錶格行,因此我可能沒有完全理解您的意思。我還沒有理解你是否想轉置表。

你可能要尋找的是:

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

df = pd.DataFrame(
    {'YYYYMM':[201603,201503,201403,201303,201603,201503,201403,201303], 
    'Count':[5,6,2,7,4,7,8,9], 
    'Group':['A','A','A','A','B','B','B','B']}) 

df['YYYYMM']=df['YYYYMM'].astype(str).str[:-2].astype(int) 

t=pd.pivot_table(df, values='Count', index='YYYYMM',columns='Group',aggfunc=np.sum) 
t.index.name = None 

fig, ax = plt.subplots(1,1) 
t.plot(table=t,ax=ax) 
ax.xaxis.set_major_formatter(plt.NullFormatter()) 

plt.tick_params(
    axis='x',   # changes apply to the x-axis 
    which='both',  # both major and minor ticks are affected 
    bottom='off',  # ticks along the bottom edge are off 
    top='off',   # ticks along the top edge are off 
    labelbottom='off') # labels along the bottom edge are off 
plt.show() 

enter image description here