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

如何使用ggplot2绘制每类x值对应双柱、带双Y轴的柱状图

双Y轴并排柱状图实现方案

ggplot2的次Y轴仅作为可视化标注使用,不直接参与数据映射,因此需要先对量级小的number类数值做缩放转换,匹配price的量级后再绘图,最后将次Y轴刻度做反向转换还原真实数值即可,具体实现如下:


1. 计算缩放系数

先基于两个指标的最大值计算缩放比例,保证转换后两类数值的柱高可比:

# 提取两类指标的最大值
max_price <- max(df$Value[df$Type == "price"])
max_num <- max(df$Value[df$Type == "number"])
# 计算缩放系数,将number数值放大到和price同量级
scale_factor <- max_price / max_num

2. 绘图代码

library(ggplot2)
library(ggpubr) # 对应你代码中用到的labs_pubr()函数

ggplot(df, aes(x = Cat, fill = Type)) +
  # 对number类数值做缩放后映射到Y轴
  geom_col(
    aes(y = ifelse(Type == "price", Value, Value * scale_factor)),
    position = position_dodge(width = 0.9),
    width = 0.7
  ) +
  # 配置双Y轴,次Y轴做反向缩放还原number真实数值
  scale_y_continuous(
    name = "price",
    sec.axis = sec_axis(~ . / scale_factor, name = "number")
  ) +
  scale_fill_grey() +
  theme_bw() +
  labs_pubr() +
  theme(
    axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
    # 可选配置:两个Y轴标题颜色对应不同柱形灰度,提升辨识度
    axis.title.y.left = element_text(color = "gray20"),
    axis.title.y.right = element_text(color = "gray60")
  )

可选补充:添加数值标签

如果需要在柱形上方标注真实数值,可在geom_col后追加以下代码:

geom_text(
  aes(
    y = ifelse(Type == "price", Value, Value * scale_factor),
    label = Value
  ),
  position = position_dodge(width = 0.9),
  vjust = -0.2,
  size = 3
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:30:04