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

Plotly发散条形图如何将y轴移至中间且两侧分别设置图例

Plotly发散条形图问题解决方案

实体名称居中显示在x轴0刻度

将y轴锚定到x轴的0刻度位置,调整刻度标签对齐方式,即可让A/B/C等实体名正好显示在0刻度中间位置。

左右两侧独立图例配置

使用Plotly多图例特性,为左右两侧的条形轨迹分别绑定独立的图例实例,分别调整位置即可实现两个互不干扰的独立图例。

完整可运行代码

import numpy as np
import pandas as pd
import plotly.graph_objects as go

d = {'Who': ['A', 'B', 'C', 'D', 'E', 'F'],
     'Pants on Fire': [9,7,6,4, 2, 1],
     'False': [7, 6, 4, 5, 2,1],
     'Mostly False': [5, 4, 6,4, 2, 6],
     'Half True' : [4,2,5,6,3, 2],
     'Mostly True': [5,3,2,3,4,3],
    'True': [2,4,3,6, 6, 8]}
df = pd.DataFrame(d)

fig = go.Figure()
# 左侧负向条形,绑定第一个图例
for col in df.columns[1:4]:
    fig.add_trace(go.Bar(x=-df[col].values,
                         y=df['Who'],
                         orientation='h',
                         name=col,
                         customdata=df[col],
                         hovertemplate = "%{y}: %{customdata}",
                         legend="legend1"))
# 右侧正向条形,绑定第二个图例
for col in df.columns[4:]:
    fig.add_trace(go.Bar(x= df[col],
                         y =df['Who'],
                         orientation='h',
                         name= col,
                         hovertemplate="%{y}: %{x}",
                         legend="legend2"))    

fig.update_layout(barmode='relative', 
                  height=400, 
                  width=900, # 加宽画布容纳两个图例
                  bargap=0.01,
                  # 配置y轴固定在x=0位置,标签居中
                  yaxis=dict(
                      autorange='reversed',
                      anchor="x",
                      position=0,
                      tickalign="center",
                      title=""
                  ),
                  # 配置第一个图例(左侧不实类)
                  legend=dict(
                      orientation='v',
                      x=-0.3,
                      y=1,
                      title_text="*不实类别*"
                  ),
                  # 配置第二个图例(右侧属实类)
                  legend2=dict(
                      orientation='v',
                      x=1.1,
                      y=1,
                      title_text="*属实类别*"
                  ),
                  # 调整x轴边距避免内容裁切
                  xaxis=dict(
                      title="",
                      ticklabelposition="outside"
                  )
                 )
fig.show()

核心调整点说明

  • 调整y轴参数anchor="x", position=0,将y轴整体固定在x轴0刻度位置,搭配tickalign="center"保证标签居中对齐
  • 给左侧负向条形轨迹新增legend="legend1"参数,右侧正向条形轨迹新增legend="legend2"参数,将两类轨迹分属不同图例
  • 在布局配置中分别定义legend和legend2两个图例的位置、标题,分别放在画布左右两侧
  • 适当加宽画布宽度,避免图例和标签被裁切

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:06:09