数据描述:
df2=df[['Marital_Status','MntWines']]
df2.head()
可以看到,Marital_Status是一个分类变量,MntWines则是一个连续变量。想根据Marital_Status对MntWines进行分组并绘制箱线图进行比较。
刚开始试图直接用plt.boxplot()进行绘制,但是plt.boxplot()值允许2D-array的输入,不能直接输入DataFrame自动分组:
于是我采用了笨方法,手动根据Marital_Status将MntWines分为几组,构成一个二维列表,然后输入plt.boxplot()。代码如下:
#boxplot of MntWines at different Marital_Status
#df.Marital_Status的类型
labels=list(set(df.Marital_Status))
labels
Mnt=[]
#进行分组
for label in labels:
Mnt.append(df[df.Marital_Status==label].MntWines)
#绘制箱线图
plt.boxplot(Mnt,labels=labels)
plt.xlabel('Marital Status')
plt.ylabel('Mount of Wines')
plt.title('boxplot of MntWines at different Marital Status')
plt.show()
如下图所示:
后来发现pandas.DataFrame里实际内置了boxplot函数,可以更方便地直接进行绘制。
boxplot方法官方介绍如下:
DataFrame.boxplot(column=None, by=None, ax=None, fontsize=None, rot=0, grid=True, figsize=None, layout=None, return_type=None, **kwds)
方法说明
boxplot方法只是用于DataFrame,Series对象没有此方法
参数说明
column,默认为None,输入为str 或由str构成的list,其作用是指定要进行箱型图分析的列
by,默认为None,str or array-like,其作用为pandas的group by,通过指定by=‘columns’,可进行多组合箱型图分析
ax,matplotlib.axes.Axes的对象,没有太大作用
fontsize,箱型图坐标轴字体大小
rot,箱型图坐标轴旋转角度
grid,箱型图网格线是否显示
figsize,箱型图窗口尺寸大小
layout,必须配合by 一起使用,类似于subplot 的画布分区域功能
return_type,指定返回对象的类型,默认为None,可输入的参数为‘axes’,‘dict’,‘both’,当与by一起使用是,返回的对象为Series或array(for return_type = None)
df2.boxplot(by='Marital_Status')
plt.show()
如图,比我们手动分组绘制方便多了。