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

使用Plotly叠加柱状图与阈值线遇问题,寻求解决方案

解决Plotly柱状图叠加阈值线的问题

以下是针对需求优化后的完整代码,同时对应解决你提出的三个问题:

import pandas as pd 
df = pd.DataFrame({'Nutriment' : ['Glucides (g)', 'Lipides (g)', 'Protéines (g)'],
      'ail' : [4, 0.056, 7.82],
      'basilic' : [0.05, 0.009, 0.42],
      'carotte' : [2.6, 0.1, 3.44],
      'citron vert' : [0.063, 0.0, 0.14]})
from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots()

ingredients = df.columns[1:]
clrs = {}
n = 100
for ingredient in ingredients : 
    clrs[ingredient] = 'rgb(0,' + str(n) + ',' + str(n) + ')'
    n += 40

# 使用默认x轴绘制堆叠柱状图,无需额外创建x2轴
for ingredient in ingredients :
    fig.add_trace(go.Bar(
        x=df['Nutriment'], 
        y=df[ingredient], 
        name=ingredient, 
        marker={'color': clrs[ingredient]}
    ))

# 针对每个营养分类绘制精准覆盖的阈值线
fig.add_trace(go.Scatter(
    x=[-0.4, 0.4], y=[4.5, 4.5], 
    name='Apport recommandé en glucides (min)', 
    line_color='#ff0040',
    mode='lines'
))
fig.add_trace(go.Scatter(
    x=[0.6, 1.4], y=[1.9, 1.9], 
    name='Apport recommandé en lipides (min)', 
    line_color='#00ff00',
    mode='lines'
))
fig.add_trace(go.Scatter(
    x=[1.6, 2.4], y=[1, 1], 
    name='Apport recommandé en protéines (min)', 
    line_color='#0000f0',
    mode='lines'
))

# 配置布局满足需求
fig.update_layout(
    width=800, 
    height=500, 
    title_text='Apports nutritionnels par portion', 
    barmode='stack',
    yaxis=dict(range=[0, None]),  # 重置y轴原点为0
    xaxis=dict(
        tickmode='array',
        tickvals=[0, 1, 2],
        ticktext=df['Nutriment'],
        showticklabels=True
    )
)

fig.show()

关键修改说明

  • 显示所有阈值线:

    • 移除冗余的x2轴配置,让柱状图与阈值线共用同一x轴;
    • 调整Scatter的x坐标范围,匹配每个分类柱子的宽度区间(默认堆叠柱宽度为0.8,对应x范围为[序号-0.4, 序号+0.4]),确保阈值线精准覆盖对应分类;
    • 添加mode='lines'明确仅绘制线条。
  • 重置网格原点为(0,0):
    通过yaxis=dict(range=[0, None])强制y轴从0开始,让网格原点对齐(0,0)。

  • 保留分类标签并删除数字刻度:
    配置x轴手动指定刻度值与对应文本,自动隐藏原始数字刻度,只显示营养分类名称。

内容的提问来源于stack exchange,提问作者Marie-Olive

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:05:15