我从3个不同的数据帧(都具有相同的键)中导入数据,并将它们放在一起成为1个单个数据帧。

df1 = read_xlsx('Means_Cent')
df2 = read_xlsx('Means_Rand')
df3 = read_xlsx('Means_Const')
df1['Key'] = 'Cent'
df2['Key'] = 'Rand'
df3['Key'] = 'Const'

df_means = pd.concat([df1,df2,df3], keys = ['Cent', 'Rand', 'Const'])


现在,我想使用DataFrame.plot()创建一个图,其中在同一图中每个键= ['Cent','Rand','Const']都有1个图。

我的数据框df_means的一部分看起来像这样:

         02_VOI  03_Solidity  04_Total_Cells
Cent  0   1.430       19.470           132.0
      1   1.415       18.880           131.0
      2   1.460       19.695           135.0
      3   1.520       19.695           141.0
Rand  0   1.430       19.205           132.0
      1   1.430       19.170           132.0
      2   1.445       19.430           133.5
      3   1.560       19.820           144.5
Const 0   1.175       22.695           108.5
      1   1.430       22.260           132.0
      2   1.180       21.090           109.0
      3   1.360       22.145           126.0


现在我想绘制02_VOI vs 04_Total_Cells,每个键应该是1张图(g1 = 02_VOI(Cent)vs 04_Total_Cells(Cent),g2 = 02_VOI(Rand)vs 04_Total_Cells(Rand)...)

我尝试使用DataFrame.unstack():

df_means.unstack(level = 0).plot(x = '02_VOI', y = '04_Total_Cells')


但这似乎弄乱了钥匙。它返回9个图形(每个VOI(Cent,Rand,Const)与Total_Cells(Cent,Rand,Const)的组合为1个图。

感谢您的帮助,我也很高兴提供有关如何更好地连接3个初始数据帧的提示。

最佳答案

我想我会使用Seaborn绘图。这要容易得多。 Seaborn喜欢"tidy"数据。

import pandas as pd
import seaborn as sns
df_mean = pd.read_clipboard()
df_mean


输出:

         02_VOI  03_Solidity  04_Total_Cells
Cent  0   1.430       19.470           132.0
      1   1.415       18.880           131.0
      2   1.460       19.695           135.0
      3   1.520       19.695           141.0
Rand  0   1.430       19.205           132.0
      1   1.430       19.170           132.0
      2   1.445       19.430           133.5
      3   1.560       19.820           144.5
Const 0   1.175       22.695           108.5
      1   1.430       22.260           132.0
      2   1.180       21.090           109.0
      3   1.360       22.145           126.0


重置索引并根据需要重命名列。

df_mean = df_mean.reset_index()
df_mean = df_mean.rename(columns={'level_0':'Groups','level_1':'Samples'})
_ = sns.lmplot(x='02_VOI',y='04_Total_Cells', data=df_mean, scatter=True, col='Groups',fit_reg=False)


python - 使用pd.DataFrame中的MultiIndex绘制数据-LMLPHP

关于python - 使用pd.DataFrame中的MultiIndex绘制数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43369237/

10-12 14:14
查看更多