使用数据集的 matplotlib 绘制箱线图
boxplots using matplotlib of a dataset
我在电子表格中有一个数据集,分为两列,类似于以下内容:
输入 [1, 0, 1, 1, 0, 0, 0, 1, 0, 0]
值 [230、300、342、218、393、273、333、317、287、291]
我想将 0 种类型和 1 种类型的值分组,并在单个框架中绘制三个数据集(原始集、0s 和 1s)的箱线图。
我尝试了一些不同的方法,但 none 奏效了:
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.
构建箱线图
您可以 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)
输出:
我在电子表格中有一个数据集,分为两列,类似于以下内容:
输入 [1, 0, 1, 1, 0, 0, 0, 1, 0, 0]
值 [230、300、342、218、393、273、333、317、287、291]
我想将 0 种类型和 1 种类型的值分组,并在单个框架中绘制三个数据集(原始集、0s 和 1s)的箱线图。
我尝试了一些不同的方法,但 none 奏效了:
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.
构建箱线图您可以 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)
输出: