python - 使用数据集的 matplotlib 绘制箱线图
问题描述
matplotlibs/boxplots 的新手。我在电子表格中有一个数据集,分两列,类似于下面
输入 [1, 0, 1, 1, 0, 0, 0, 1, 0, 0]
值 [230, 300, 342, 218, 393, 273, 333, 317, 287, 291]
我想将 0 类型和 1 类型的值分组,并将三个数据集(原始集、0 和 1)绘制在一个帧中。
我尝试了一些不同的方法,但都没有奏效:
import matplotlib.pyplot as plt
import numpy
import pandas a pd
inData = pd.read_csv(sheet)
x = inData['value']
grouped = inData.groupby(["type"])
out0, out1 = [grouped.get_group(value) for value in grouped.groups]
fig1, ax1 = plt.subplots()
ax1.set_title('Box Plot')
data = [out0, value, out1[::2]]
ax1.boxplot(data)
plt.show()
Boxplot 必须使用 python/matplotlibs 构建
任何帮助表示赞赏。
解决方案
您可以concat
在分配组合标签时将数据集与自身一起使用,然后使用seaborn.boxplot
:
import seaborn as sns
df = pd.DataFrame({'type': [1, 0, 1, 1, 0, 0, 0, 1, 0, 0],
'value': [230, 300, 342, 218, 393, 273, 333, 317, 287, 291]
})
sns.boxplot(data=pd.concat([df, df.assign(type='both')]),
x='type', y='value', order=['both', 0, 1]
)
输出:
纯matplotlib解决方案
df = pd.DataFrame({'type': [1, 0, 1, 1, 0, 0, 0, 1, 0, 0],
'value': [230, 300, 342, 218, 393, 273, 333, 317, 287, 291]
})
df2 = pd.concat([df, df.assign(type='both')]).groupby('type')['value'].apply(list)
ax = plt.subplot()
ax.boxplot(df2, labels=df2.index)
输出:
推荐阅读
- php - Preg_replace 在 laravel 控制器中不起作用
- java - Java 将 char 数组长度打印为 0,即使我已为其分配了长度
- python - 基于文本的冒险挑战问题
- android - 如何在 webview 应用程序中使用谷歌登录?
- node.js - 如何在 AWS Elastic Beanstalk 上运行 TypeORM 迁移命令
- python - 是否可以在单个应用程序中运行两个 YOLO (yolov4) 对象检测模型?
- cuda - 在没有实际张量核心的情况下,我如何能够运行张量核心指令?
- inform7 - Inform 7 要求在一定时间范围内输入
- c# - 登录后如何让用户回到原来的页面?
- python - Django TypeError:“datetime.datetime”类型的参数不可迭代