【发布时间】:2021-03-26 01:03:58
【问题描述】:
我正在尝试制作类似 SO-answer for matplotlib 中的嵌套箱线图,但我无法弄清楚如何创建我的数据框。
这样做的目标是对表示对象位置(3D)的 PCA 模型进行某种敏感性分析;根据我正在使用的 PCA 组件的数量,我可以在其中看到 PCA 模型能够很好地表示类似拱形的分布。
所以我有一个形状数组 (n_pca_components, n_samples, n_objects),其中包含对象到它们在拱形上的“理想”位置的距离。我能够进行箱线图的是(显示随机数据的示例):
这是 - 我假设 - 一个聚合箱线图(在我的数组的前两个轴上收集的统计数据);我想创建一个具有相同 x 轴和 y 轴的箱线图,但是对于每个“obj_..”,我想要一个沿数据第一个轴的每个值的箱线图(n_pca_components),即类似这样的东西(其中天对应于“obj_i”,“total_bill”对应于我存储的距离,“吸烟者”对应于数组第一个轴上的每个条目。
我四处阅读,但迷失在 panda 的多索引、groupby、(un)stack、reset_index 等概念中……我看到的所有示例都有不同的数据结构,我认为这就是问题所在,我没有'尚未做出心理'点击'并且正在考虑错误的数据结构。
到目前为止我所拥有的是(使用随机/示例数据):
n_pca_components = 5 # Let's say I want to make this analysis for using 3, 6, 9, 12, 15 PCA components
n_objects = 14 # 14 objects per sample
n_samples = 100 # 100 samples
# Create random data
mses = np.random.rand(n_pca_components, n_samples, n_objects) # Simulated errors
# Create column names
n_comps = [f'{(i+1) * 3}' for i in range(n_pca_components)]
object_ids = [f'obj_{i}' for i in range(n_objects)]
samples = [f'sample_{i}' for i in range(n_samples)]
# Create panda dataframe
mses_pd = mses.reshape(-1, 14)
midx = pd.MultiIndex.from_product([n_comps, samples], names=['n_comps', 'samples'])
mses_frame = pd.DataFrame(data=mses_pd, index=midx, columns=object_ids)
# Make a nested boxplot with `object_ids` on the 'large' X-axis and `n_comps` on each 'nested' X-axis; and the box-statistics about the mses stored in `mses_frame` on the y-axis.
# Things I tried (yes, I'm a complete pandas-newbie). I've been reading a lot of SO-posts and documentation but cannot seem to figure out how to do what I want.
sns.boxplot(data=mses_frame, hue='n_comps') # ValueError: Cannot use `hue` without `x` and `y`
sns.boxplot(data=mses_frame, hue='n_comps', x='object_ids') # ValueError: Could not interpret input 'object_ids'
sns.boxplot(data=mses_frame, hue='n_comps', x=object_ids) # ValueError: Could not interpret input 'n_comps'
sns.boxplot(data=mses_frame, hue=n_comps, x=object_ids) # ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
【问题讨论】: