樣本數據的一年:並排側的一個大熊貓數據幀的多個列的箱線圖
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)
謝謝您的回答。對不起,如果我的主要職位一直不清楚。如果你能幫我改進,我會很高興。我將在一分鐘內編輯我在原始文章中找到的解決方法/解決方案,以幫助澄清我的意思。 –