如何在Plotly Strip图中添加均值标记?
在Plotly Express Strip图中添加均值标记
要在Plotly Express绘制的Strip图中添加分组均值标记,需先计算各组薪资均值,再通过plotly.graph_objects添加散点标记实现,具体步骤如下:
完整实现代码
import pandas as pd import numpy as np import plotly.express as px import plotly.graph_objects as go # 生成模拟数据 data = pd.DataFrame( { 'job_title': np.random.choice(['data_science', 'Data_analysis'], 400), 'experience_level': np.random.choice(['entry', 'senior'], 400), 'salary': np.random.randint(30000, 80000, 400) # 生成更贴合实际的薪资范围 } ) data = data.sort_values(by='experience_level', ascending=True) # 绘制基础Strip图 fig = px.strip(data, x='job_title', y='salary', color='experience_level') # 计算分组薪资均值 mean_data = data.groupby(['job_title', 'experience_level'])['salary'].mean().reset_index() # 为每个分组添加均值标记 for idx, row in mean_data.iterrows(): fig.add_trace(go.Scatter( x=[row['job_title']], y=[row['salary']], mode='markers', marker=dict(size=12, color=fig.data[idx].marker.color), # 匹配原Strip图的分组颜色 name=f"{row['experience_level']} 均值", showlegend=False # 避免图例重复 )) # 调整布局 fig.update_layout(width=800, height=600, title='岗位薪资分布及均值标记') fig.show()
关键步骤说明
- 计算分组均值:通过
groupby按job_title和experience_level分组,计算每组薪资的平均值,得到包含均值信息的数据集。 - 添加均值标记:遍历均值数据集,使用
go.Scatter添加散点标记,通过fig.data[idx].marker.color匹配原Strip图的分组颜色,保证视觉一致性;设置较大的标记尺寸让均值点更醒目,关闭重复图例。 - 数据优化:将原代码中
np.random.choice((50000),400)替换为np.random.randint(30000,80000,400),生成更符合实际场景的薪资数据。
内容的提问来源于stack exchange,提问作者Manish Patel
相关产品推荐
相关产品推荐

