python - 将数据导入 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'])
我也希望不必按标题指定每个单独的列,而是自动选择文件中的所有列。
非常感谢所有反馈和输入!
解决方案
像这样的东西应该工作:
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('')
推荐阅读
- rhel - Forgerock - Forgeops - util - 使用 RHEL 构建?
- python - 使用箭头键移动 pygame 目标图像(范围)的问题
- javascript - 如果较低的 div 包含特定文本,则将 DIV 隐藏在另一个 div 上方几级
- material-ui - 使用 Material-UI,最新的 Next.js 9 实现示例具有无样式的内容
- azure - 如何使用 Azure 应用服务 /web 别名?
- sql-server - 如何在 SQL Server 中使用 PATINDEX?
- office365 - 下载大于 4MB 的附件
- iis - 如何将 HTTP 标头信息传递到在代理后面运行的 SonarQube 服务器?
- ios - 尝试使用 KWStepper 自定义 UI 步进器 pod 时出现“不支持 NSCoding”
- ruby-on-rails - 自定义 ransacker args 的表单助手 - Rails