使用数据集的matplotlib进行箱线图

2024-06-01 01:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

新手到matplotlibs/boxplots。我在电子表格中有一个数据集,分为两列,如下所示

键入[1,0,1,1,0,0,0,1,0,0]

值[230300342182183333317287291]

我想对0类型和1类型的值进行分组,并在单个帧中对三个数据集(原始集、0和1)进行箱线图绘制

enter image description here

我尝试了一些不同的方法,但都没有成功:

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()

必须使用python/matplotlibs构建箱线图

感谢您的帮助


Tags: 数据import类型datavaluepltpd新手
1条回答
网友
1楼 · 发布于 2024-06-01 01:19:17

您可以在分配组合标签时concat使用数据集本身,然后使用^{}

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]
           )

输出:

seaborn boxplot

纯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 boxplot per group

相关问题 更多 >