2017-03-13 106 views
6

樣本數據的一年:並排側的一個大熊貓數據幀的多個列的箱線圖

import pandas as pd 
import numpy.random as rnd 
import seaborn as sns 
n = 365 
df = pd.DataFrame(data = {"A":rnd.randn(n), "B":rnd.randn(n)+1}, 
        index=pd.date_range(start="2017-01-01", periods=n, freq="D")) 

我想箱線圖這些數據並排側按月(即兩個箱子每個分組月,一個用於A,另一個用於B)。對於單列sns.boxplot(df.index.month, df["A"])工作正常。但是,sns.boxplot(df.index.month, df[["A", "B"]])將引發錯誤(ValueError: cannot copy sequence with size 2 to array axis with dimension 365)。根據索引(pd.melt(df, id_vars=df.index, value_vars=["A", "B"], var_name="column"))熔化數據以便將seaborn的hue屬性用作解決方法也不起作用(TypeError: unhashable type: 'DatetimeIndex')。

(A解決方案並不一定需要使用seaborn,如果是比較容易使用普通matplotlib。)

/編輯:我發現了一個解決辦法,基本上產生我想要的東西。但是,一旦DataFrame包含比我想繪製的變量更多的變量,就會變得有些尷尬。因此,如果有更優雅/直接的方式來做到這一點,請分享!

df_stacked = df.stack().reset_index() 
df_stacked.columns = ["date", "vars", "vals"] 
df_stacked.index = df_stacked["date"] 
sns.boxplot(x=df_stacked.index.month, y="vals", hue="vars", data=df_stacked) 

產地: Side-by-side boxplot of A and B, grouped by month.

回答

0

我不完全理解你的問題,但你可能要看看使用matplotlib這種方法。不是最好的解決方案。

1)month分手吧df成12個DataFrames,所有堆疊在列表

DFList = [] 
for group in df_3.groupby(df_3.index.month): 
    DFList.append(group[1]) 

2)畫出它們的其他在一個循環之後的一個:

for _ in range(12): 
    DFList[_].plot(kind='box', subplots=True, layout=(2,2), sharex=True, sharey=True, figsize=(7,7)) 

plt.show() 

3)這裏的一個前三行快照:

enter image description here

你也可能要籤matplotlibadd_subplot method

+0

謝謝您的回答。對不起,如果我的主要職位一直不清楚。如果你能幫我改進,我會很高興。我將在一分鐘內編輯我在原始文章中找到的解決方法/解決方案,以幫助澄清我的意思。 –