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

ggplot组合图添加折线百分比标签及修正图例异常问题

解决ggplot组合图的两个问题

修改后的完整代码

library(ggplot2)
library(scales)

name <- rep(c("ba", "EW", "RW", "Se", "St", "US", "VN"), 2)
value <-  c(0, 6323, 7397, 13945, 11801, 55255, 22519, 4124, 13540, 9616, 57724, 6646, 22021, 8841)
type <- c(rep("g", 7), rep("o", 7))
test <- data.frame(name, value, type)

name2 <- c("ba", "EW", "RW", "Se", "St", "US", "VN")
share <- c(1, .61, .47, .8, .34, .28, .28) 
test2 <- data.frame(name2, share)

scaling_factor <- 8e4

ggplot(test, aes(x=name, y=value, fill=type)) + 
  geom_bar(position = position_stack(reverse = TRUE), stat='identity') + 
  scale_fill_manual(values = c("#0099f9", "#69c6ff"), name = "柱状图") + 
  # 柱状图数值标签
  geom_text(aes(label = value), position = position_stack(vjust = 0.5, reverse = TRUE), 
            colour = "black", size = 3) + 
  # 折线:将颜色映射到aes以生成独立图例
  geom_line(data = test2, 
            aes(x = name2, y = share * scaling_factor, color = "折线", group = 1), 
            size = 1) + 
  # 折线点:复用颜色映射
  geom_point(data = test2, 
             aes(x = name2, y = share * scaling_factor, color = "折线", group = 1), 
             size = 3) + 
  # 折线百分比标签:偏移y轴位置避免重叠,格式化百分比
  geom_text(data = test2, 
            aes(x = name2, y = share * scaling_factor * 1.05, label = percent(share), group = 1),
            color = "orange", size = 3, vjust = 0) + 
  # 设置y轴和次轴
  scale_y_continuous(name = "axis 1", 
                     sec.axis = dup_axis(~./scaling_factor, name = "axis 2", labels = percent)) + 
  # 设置折线颜色,分离图例
  scale_color_manual(values = c("折线" = "orange"), name = "折线图") + 
  # 调整图例位置和顺序(可选)
  guides(fill = guide_legend(order = 1), color = guide_legend(order = 2))

问题1:添加折线百分比标签无重叠

  • 单独用geom_text为折线添加标签,指定data=test2,并将y值设置为share * scaling_factor * 1.05,让标签位于折线点的上方,避免与柱状图内部的数值标签重叠
  • 使用scales::percent()将share格式化为百分比格式,提升可读性

问题2:分离折线与柱状图图例

  • 将折线和点的color参数移入aes()中,映射为固定字符串(比如"折线"),让ggplot为其生成独立的图例
  • 通过scale_color_manual()指定折线的橙色,并设置图例名称
  • 用guides()可调整两个图例的显示顺序,优化布局

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:53:11