首页 > 解决方案 > 使用数据集的 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 构建

任何帮助表示赞赏。

标签: pythonmatplotlibboxplot

解决方案


您可以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)

输出:

每组 matplotlib 箱线图


推荐阅读