2014-03-05 64 views
0

我想繪製特定列的條形圖和折線圖。繪製DataFrame聚合後的特定列

使用agg函數我有很多新的列,因爲有功能。 如果我想只繪製列總和A和平均值B列?

enter image description here

下面你可以找到我的代碼,所有列繪製。

index=pd.date_range('2013-1-1 00:00', '2013-12-31 23:00', freq='1h') 
df=pd.DataFrame(np.random.rand(len(index),2),index=index, columns=['A','B']) 

df2=df.groupby(lambda x: x.month).agg({'A' : [np.mean, np.sum], 'B': np.mean}) 

fig = plt.figure() 
ax = df2['A'].plot(kind="bar");plt.xticks(rotation=0) 
ax2 = ax.twinx() 
ax2.plot(ax.get_xticks(),df2['B'],marker='o') 

能幫你能夠給我一些提示如何解決這個問題? 提前謝謝!

回答

3

您有一個分層索引。所以你只需要使用tuple語法選擇正確的列。

所以不是:

ax = df2['A'].plot(kind="bar") 

使用:

ax = df2[('A', 'sum')].plot(kind="bar") 

,而不是和:

ax2.plot(ax.get_xticks(),df2['B'],marker='o') 

使用:

ax2.plot(ax.get_xticks(),df2[('B', 'mean')],marker='o') 

全部放在一起:

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

np.random.seed(0) 

index = pd.date_range('2013-1-1 00:00', '2013-12-31 23:00', freq='1h') 
df = pd.DataFrame(np.random.rand(len(index),2),index=index, columns=['A','B']) 
df2 = df.groupby(lambda x: x.month).agg({'A' : [np.mean, np.sum], 'B': np.mean}) 

fig = plt.figure() 
ax = df2[('A', 'sum')].plot(kind="bar", alpha=0.7) 
plt.xticks(rotation=0) 
ax2 = ax.twinx() 
ax2.plot(ax.get_xticks(),df2[('B', 'mean')],marker='o', c='navy', linewidth=4) 

爲您提供了一個很好的圖形: enter image description here

+0

你知道如何在這個圖表圖例?使用標籤似乎不起作用... – Michal