python分组绘制箱型图

python绘制箱型图十分简单,而且有很多种方法可以实现,可以看看这篇文章,多种python箱型图绘制方法。但是奇怪的是网上竟然都搜不到分组绘制箱型图的方法。所谓分组绘制箱型图就是首先对数据进行一个groupby操作,然后对每个group绘制一下箱型图。R的话就用ggplot2就行了,也有很多教程,但是基于python的似乎还没有,实际上基础的plt和dataframe自带的boxplot方法确实是无法分组绘制的,想要实现这个功能需要使用searborn包才可以的。分组绘制箱型图传送门。这个链接中就是seaborn的boxplot的方法,由于是中文的也写的很清楚了,就不做过多解释了。下面贴一下我写的一个分组绘制箱型图代码吧。

plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
# plt.rcParams['savefig.dpi'] = 300 #图片像素
# plt.rcParams['figure.dpi'] = 300 #分辨率
# plt.figure(figsize=(50, 5))
sns.boxplot(x='groupfield', y='data', hue='groupfield', data=tmp , color = 'g' , linewidth = 0.5 , fliersize = 1)
sns.despine(offset=10, trim=True)
plt.xticks(rotation=90)
# plt.legend(markerscale = 5 , bbox_to_anchor=(1.4,0.8))
plt.show()

里面的tmp是一个dataframe,有两列。格式类似于下面这样,以上的代码就是实现了以groupfield 这个字段作为分组依据,分组后用data绘制箱型图这样一个功能,十分简单。

groupfielddata
A$1600
A$12
B$1
### 使用 Matplotlib 和 Seaborn 绘制箱型图 #### 导入必要的库 为了使用 `matplotlib` 和 `seaborn` 进行绘图,首先需要导入这些库。如果尚未安装这两个库,则可以通过命令 `pip install matplotlib seaborn` 安装[^1]。 ```python import matplotlib.pyplot as plt import seaborn as sns import pandas as pd ``` #### 创建样本数据集 创建一个简单的 Pandas DataFrame 来模拟实际应用中的情况。这里构建了一组不同类别的数值数据以便于展示箱型图的功能。 ```python data = { 'Category': ['A', 'B', 'C'] * 30, 'Values': (list(range(30)) + list(range(28, -2, -2)) + [7]*30) } df = pd.DataFrame(data) print(df.head()) ``` #### 使用 Matplotlib 绘制箱型图 可以直接调用 `plt.boxplot()` 方法并传入相应的参数来绘制基本的箱型图。对于分类变量的情况,可以先按类别分组再分别绘制每个类别的箱型图。 ```python fig, ax = plt.subplots() for category in df['Category'].unique(): subset = df[df['Category'] == category]['Values'] positions = [ord(category)-64] # 将'A'转换成位置1,'B'->2... bp = ax.boxplot(subset, positions=positions, widths=0.6) ax.set_xticklabels(['A', 'B', 'C']) plt.title('Box Plot using Matplotlib') plt.xlabel('Categories') plt.ylabel('Value Distribution') plt.show() ``` #### 使用 Seaborn 绘制更加美观的箱型图 相比于原生的 `matplotlib` 接口,`seaborn` 提供了更为简洁易读的方法——`sns.boxplot()`,能够快速生成带有更多默认样式优化后的箱型图,并且支持更多的自定义选项[^3]。 ```python plt.figure(figsize=(8, 6)) sns.boxplot(x='Category', y='Values', data=df, palette="Set3") plt.title('Box Plot with Seaborn') plt.xlabel('Categories') plt.ylabel('Value Distributions') # 显示异常点的具体数值标签 fliers = [] # 存储所有的离群点坐标 for line in plt.gca().get_lines(): if line.get_marker() not in ["None", ""]: fliers.extend(line.get_data()[1]) for fly in fliers: plt.text(fly+0.1, fly, str(round(fly)), ha='left', va='center') plt.tight_layout() plt.show() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值