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

如何在Plotly的两个子图之间放置y轴刻度与变量名称?

实现Plotly双向条形图中间放置变量名称与y轴刻度

完全可以实现,只需调整子图的y轴显示设置,把右侧子图的y轴移到两个子图中间,同时隐藏左侧子图的y轴即可。以下是修改后的完整代码:

修改后代码

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

data = {'variable': {0: 'Case', 1: 'Exam', 2: 'History', 3: 'MAP', 4: 'Volume'},
 'margins_fluid': {0: 0.497, 1: 0.668, 2: 0.506, 3: 0.489, 4: 0.718},
 'margins_vp': {0: 0.809, 1: 0.893, 2: 0.832, 3: 0.904, 4: 0.92}}

df = pd.DataFrame(data)

fig = make_subplots(
    rows=1,
    cols=2,
    shared_xaxes=False,
    shared_yaxes=False,  # 关闭共享y轴,方便单独设置
    horizontal_spacing=0.08,  # 增大间距给中间的y轴标签留出空间
    subplot_titles=['<b>Fluid</b>', '<b>Vasopressor</b>'])

# 左侧子图:Fluid
fig.append_trace(
    go.Bar(
        x=df['margins_fluid'],
        y=df.index,  # 改用索引,避免重复显示y轴标签
        text=df["margins_fluid"], 
        textposition='inside',
        texttemplate="%{x:.4p}",
        orientation='h', 
        width=0.7,
        showlegend=False, ), 
        1, 1)

# 右侧子图:Vasopressor
fig.append_trace(
    go.Bar(
        x=df['margins_vp'],
        y=df.index,  # 用索引对齐两个子图的y轴
        text=df["margins_vp"],
        textposition='inside',
        texttemplate="%{x:.4p}",
        orientation='h', 
        width=0.7, 
        showlegend=False), 
        1, 2)

# 调整左侧子图:反转x轴,隐藏y轴
fig.update_xaxes(
    tickformat=',.0%', 
    row=1,
    col=1,
    autorange='reversed',
    range=[1, 0]  # 固定范围,避免条形图挤压中间标签
)
fig.update_yaxes(
    visible=False,  # 隐藏左侧y轴
    row=1, col=1
)

# 调整右侧子图:设置x轴范围,将y轴移到中间并显示变量名称
fig.update_xaxes(
    tickformat=',.0%', 
    row=1,
    col=2,
    range=[0, 1]
)
fig.update_yaxes(
    tickmode='array',
    tickvals=df.index,
    ticktext=df['variable'],  # 替换为变量名称
    side='left',  # 将y轴移到子图左侧,即两个子图中间
    showgrid=False,
    row=1, col=2
)

fig.update_layout(
    title_text="双向条形图(变量名称居中)",
    barmode="group",
    width=800, 
    height=700,
    title_x=0.5,
)

fig.show()

关键修改说明

  • 关闭共享y轴,改用索引对齐两个子图的y轴,避免自动同步的冲突
  • 隐藏左侧子图的y轴,将右侧子图的y轴设置为side='left',使其显示在两个子图中间
  • 增大horizontal_spacing,给中间的y轴标签留出足够显示空间
  • 固定x轴范围,防止条形图宽度变化挤压中间的标签区域
  • 通过ticktext将y轴刻度替换为变量名称,实现精准对齐

最终效果

修改后的图表会在两个条形图中间显示变量名称(Case、Exam等),y轴刻度也对应居中,左右两侧的条形图分别对应Fluid和Vasopressor的数值,完全匹配需求布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:55:31