Seaborn并排绘制两列的箱形图

时间:2018-09-18 18:15:18

标签: python seaborn

我想绘制熊猫数据框的两列,作为按类别并排的箱形图。这与此处显示的问题不同:Grouped boxplot with seaborn,其中两列内部都有列表。那里的解决方案对我不起作用。

MWE

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
[
[2, 4, "A"],
[4, 5, "C"],
[5, 4, "B"],
[10, 4.2, "A"],
[9, 3, "B"],
[3, 3, "C"]
], columns=['data1', 'data2', 'Categories'])

#Plotting by seaborn
fig, axs = plt.subplots(1, 1)
sns.boxplot(data=df,x="Categories",y='data1',ax=axs)
fig.show()
plt.waitforbuttonpress()
plt.close(fig)

上面的代码生成: enter image description here

在箱线图中用“ data2”替换“ data1”将得到: enter image description here

我想要的是这样的: enter image description here

2 个答案:

答案 0 :(得分:1)

您首先需要melt DataFrame(转换为长格式):

data = df.melt(id_vars=['Categories'], var_name='dataset', value_name='values')
print(data)

打印:

   Categories dataset  values
0           A   data1     2.0
1           A   data2     4.0
2           C   data1     4.0
3           C   data2     5.0
4           B   data1     5.0
5           B   data2     4.0
6           A   data1    10.0
7           A   data2     4.2
8           B   data1     9.0
9           B   data2     3.0
10          C   data1     3.0
11          C   data2     3.0

现在,您只需要使用dataset作为色相即可。由于剧情非常繁忙,我将图例移到了剧情之外。

sns.boxplot(data=data, x='Categories', y='values', hue='dataset')
plt.legend(title='dataset', loc='upper left', bbox_to_anchor=(1, 1))

enter image description here

由OP编辑

我在一个函数中实现了它,使得它可以使斧头中的图具有所需的任意多列并返回。

def box_plot_columns(df,categories_column,list_of_columns,legend_title,y_axis_title,**boxplotkwargs):
    columns = [categories_column] + list_of_columns
    newdf = df[columns].copy()
    data = newdf.melt(id_vars=[categories_column], var_name=legend_title, value_name=y_axis_title)
    return sns.boxplot(data=data, x=categories_column, y=y_axis_title, hue=legend_title, **boxplotkwargs)

用法示例:

fig, ax = plt.subplots(1,1)
ax = box_plot_columns(Data,"Categories",["data1","data2"],"dataset","values",ax=ax)
ax.set_title("My Plot")
plt.show()

答案 1 :(得分:1)

尝试一下:

df = pd.DataFrame(
[
[2, 4, "A"],
[4, 5, "C"],
[5, 4, "B"],

[10, 4.2, "A"],
[9, 3, "B"],
[3, 3, "C"]
], columns=['data1', 'data2', 'Categories'])

#Plotting by seaborn
df_c = pd.melt(df, "Categories", var_name="data1", value_name="data2")
sns.factorplot("Categories",hue="data1", y="data2", data=df_c, kind="box")