首页 > 解决方案 > 将数据导入 Seaborn Boxplot 的困难

问题描述

编辑:下面的用户#kgoettler 提供了一个解决方案。问题源于 Seaborn Boxplot 要求数据按 x 轴中的变量和 y 轴中的值进行组织。下面的脚本将数据重新组织成与 Seaborn Boxplot 兼容的形式。

原始问题:我的目标是使用 CSV 文件中的数据生成箱线图。我想使用 Python 可视化库 Seaborn。数据使用公共索引(对象)和每列的标题进行组织。

原始数据图像

我很难使用格式将此数据导入箱线图

seaborn.boxplot(x="variable", y="value")

使用 Pandas 自己的箱线图这不是问题,因为我只是使用以下格式根据标题指定要使用的列

boxplot = data.boxplot(column=['header1', 'header2', 'header3'])

使用原始数据的熊猫箱线图图像

我也希望不必按标题指定每个单独的列,而是自动选择文件中的所有列。

非常感谢所有反馈和输入!

标签: pythonpandascsvseaborn

解决方案


像这样的东西应该工作:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
sns.set(style='whitegrid')

csv_file = '/path/to/file.csv'
df = pd.read_csv(csv_file)
df = (df
        .set_index(['Object'])          # Set 'Object' column to index
        .rename_axis("Metric", axis=1)  # Rename the column axis "Metric"
        .stack()                        # Stack the columns into the index
        .rename('Score')                # Rename the remaining column 'Score'
        .reset_index()                  # Reset the index
    )

这应该为您提供一个如下所示的 DataFrame:

   Object                       Metric     Score
0     MT1  B1A1 Average Splaying Score  0.426824
1     MT1  B1A2 Average Splaying Score  0.431351
2     MT1  B1A3 Average Splaying Score  1.941473
3     MT2  B1A1 Average Splaying Score -0.021672
4     MT2  B1A2 Average Splaying Score  3.357387

然后进行绘图,您所要做的就是:

fig, ax = plt.subplots(figsize=(10,6))
ax = sns.boxplot(x='Metric', y='Score', data=df, ax=ax)
ax.set_xlabel('')

示例图


推荐阅读