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

Plotly Subplot背靠背图左右X轴刻度宽度不一致的解决方法

解决Plotly Subplot背靠背条形图X轴刻度宽度不一致问题

你使用plotly::subplot创建背靠背条形图时,遇到了左侧X轴10%刻度宽度与右侧不一致的问题,原代码如下:

library(plotly)

df <- data.frame(x = c("A", "B", "C"), a = c(0.1, 0.2, 0.3), b = c(0.1, 0.2, 0.6))

p1 <- plot_ly(df) %>% 
  add_bars(x = ~a, y = ~x) %>% 
  layout(xaxis = list(tickformat = ".0%", autorange = "reversed"))

p2 <- plot_ly(df) %>% 
  add_bars(x = ~b, y = ~x) %>% 
  layout(xaxis = list(tickformat = ".0%"))

subplot(p1, p2, shareY = TRUE, shareX = TRUE, nrows = 1, margin = 0)

问题原因

两个子图的X轴范围不匹配:左侧X轴的数值范围是0~0.3(反转后显示为30%到0%),右侧X轴范围是0~0.6,相同百分比刻度对应的实际像素宽度因此不一致。

解决方案

方法1:统一Subplot的X轴范围

手动设置两个子图的X轴范围为相同的绝对值区间,确保刻度宽度一致:

library(plotly)

df <- data.frame(x = c("A", "B", "C"), a = c(0.1, 0.2, 0.3), b = c(0.1, 0.2, 0.6))

# 取两侧数据的最大值,作为统一的X轴范围边界
max_val <- max(df$a, df$b)

p1 <- plot_ly(df) %>% 
  add_bars(x = ~a, y = ~x) %>% 
  layout(xaxis = list(
    tickformat = ".0%", 
    autorange = "reversed",
    range = c(max_val, 0)  # 左侧X轴从最大值到0
  ))

p2 <- plot_ly(df) %>% 
  add_bars(x = ~b, y = ~x) %>% 
  layout(xaxis = list(
    tickformat = ".0%",
    range = c(0, max_val)  # 右侧X轴从0到最大值
  ))

subplot(p1, p2, shareY = TRUE, shareX = TRUE, nrows = 1, margin = 0)

方法2:单图实现背靠背条形图(推荐)

将左侧数据取负值,在同一个图中绘制左右两侧条形,X轴天然对称,彻底避免刻度不一致问题:

library(plotly)

df <- data.frame(x = c("A", "B", "C"), a = c(0.1, 0.2, 0.3), b = c(0.1, 0.2, 0.6))
max_val <- max(df$a, df$b)

plot_ly(df) %>%
  # 左侧条形:a取负值,水平方向绘制
  add_bars(x = ~-a, y = ~x, name = "a", orientation = "h") %>%
  # 右侧条形:正常绘制b值
  add_bars(x = ~b, y = ~x, name = "b", orientation = "h") %>%
  layout(
    xaxis = list(
      tickformat = ".0%",
      # 设置刻度值和显示文本,让左侧刻度显示正百分比
      tickvals = seq(-max_val, max_val, 0.1),
      ticktext = paste0(abs(seq(-max_val, max_val, 0.1)) * 100, "%")
    ),
    barmode = "overlay"  # 覆盖模式让条形对齐Y轴
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:15:29