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
相关产品推荐
相关产品推荐

