如何标记图中的平均点?

问题描述 投票:0回答:1

我需要帮助在该图中添加标记或均值符号,如图所示。 (下图显示了我想要的结果。)

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px

data = pd.DataFrame({'job_title':np.random.choice(['data_science','Data_analysis'],400),
              'experience_level':np.random.choice(['entry','senior'],400),
              'salary':np.random.choice((50000),400)})
data.head(1)
data= data.sort_values(by='experience_level', ascending=True)
fig = px.strip(data, x='job_title', y='salary', color='experience_level')

fig.update_layout(width=800, height=600)
fig.show()

python plot plotly mean
1个回答
0
投票

似乎没有直接的解决方案,但我想我找到了解决这个问题的方法:

fig = px.strip(data, x='job_title', y='salary', color='experience_level')

# Calculate mean points for each strip category
mean_points = data.groupby(['job_title', 'experience_level'])['salary'].mean().reset_index()

然后我们必须为每个平均值绘制一个圆:

for index, row in mean_points.iterrows():
    # Create an offset for "entry" and "senior" points
    offset = 50 if row["experience_level"] == "entry" else -50

    # Use anchor to position the shape on the right strip
    fig.add_shape(type='circle',
                  xsizemode='pixel', ysizemode='pixel',
                  xanchor=row["job_title"],
                  yanchor=row["salary"],
                  x0=-5 + offset, x1=5 + offset,
                  y0=-5, y1=5,
                  line=dict(color='black', width=2),
                  fillcolor='red' if row["experience_level"] == "entry" else 'blue',
                  opacity=1)

我使用锚点来相对设置圆的坐标。确实row["job_title"]是一个字符串,用它来计算比较复杂。

根据经验水平,我使用不同的偏移量来移动 x 轴上的圆(并且我还更改了颜色)。

然后你可以绘制它:

fig.update_layout(width=800, height=600)
fig.show()

结果:

此解决方案的一个问题是我们使用像素(硬编码)值,但我们可以通过使偏移量随图形大小变化来轻松改进它。

希望对你有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.