You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly分组柱状图中添加统计显著性标记星号?

在Plotly分组柱状图中添加统计显著性星号的实现方法

核心结论

Plotly完全支持添加这类显著性标记,你可以通过**添加注释(Annotations)**来实现,无需手动绘制。下面是针对你提供的代码的修改方案:

修改后的完整代码

import plotly.graph_objects as go
import pandas as pd

HD = pd.read_excel(r'data.xlsx')
xx = list(HD['t'])
y1 = list(HD['y1'])
y2 = list(HD['y2'])
c1 = list(HD['sd1'])
c2 = list(HD['sd2'])

fig = go.Figure(data=[
    go.Bar(name='a', x=xx, y=y1, error_y=dict(
            type='data', # value of error bar given in data coordinates
            array=c1,
            visible=True)),
         
    go.Bar(name='b', x=xx, y=y2, error_y=dict(
            type='data', # value of error bar given in data coordinates
            array=c2,
            visible=True),
        textfont_size=18,
        textfont_color='red'
        )
])

# 添加显著性星号注释
annotations = []
# 示例:假设所有组都有最高等级显著性,实际根据你的统计结果替换标记
significance_marks = ['***'] * len(xx)

for i in range(len(xx)):
    # 星号x位置:取组的中心坐标,确保在两个柱子中间
    x_pos = xx[i]
    # 星号y位置:取该组含误差棒的最高值,再加偏移避免重叠
    max_y = max(y1[i] + c1[i], y2[i] + c2[i])
    y_pos = max_y + 5  # 偏移量可根据图表高度调整
    
    annotations.append(
        dict(
            x=x_pos,
            y=y_pos,
            text=significance_marks[i],
            showarrow=False,
            font=dict(
                size=20,
                color='black'
            ),
            xanchor='center',
            yanchor='bottom'
        )
    )

fig.update_layout(annotations=annotations)

fig.update_xaxes(range = [5,70])
fig.update_yaxes(range = [0,110])

fig.update_layout(barmode='group',xaxis=dict(title='b'),yaxis=dict(title="a"))
fig.update_layout(title_text='title', title_x=0.5)

fig.write_image(r'image.png')
fig.show()

关键说明

  • 位置校准:分组柱状图的组内柱子默认存在偏移,取每组原始x值作为星号的x坐标,可确保星号位于两个柱子正中间上方;y坐标取该组含误差棒的最高值加固定偏移,避免与误差棒重叠。
  • 标记自定义:significance_marks列表可根据统计结果替换为对应标记(比如*代表p<0.05,**代表p<0.01,***代表p<0.001),无显著性差异的组可留空或跳过添加注释。
  • 样式调整:通过font参数可修改星号的大小、颜色,y_pos的偏移量可根据图表整体高度灵活调整,保证视觉协调。

内容的提问来源于stack exchange,提问作者user22449488

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:05:55