ggplot绘图时如何在已有填充图例基础上新增折线线型图例
实现方案
核心逻辑:ggplot2 仅会为aes()内部映射的美学属性自动生成图例,原代码中两条折线的linetype是写在aes()外的固定参数,不会触发生成图例。只需将线型映射为自定义分类,再手动匹配线型值即可。
修改后的完整代码
x <- c(1:3) y1 <- c(2/28,13/35,43/65) y2 <- c(1/2, 2/13, 5/43) df <- data.frame(x, y1, y2) x <- c(rep(1 , 5) , rep(2 , 5) , rep(3 , 5)) condition <- rep(c("1", "2", "3", "4", "5") , 3) y3 <- c(1, 0, 0, 0, 0, 6, 4, 1, 0, 0, 12, 13, 5, 5, 3) df2 <- data.frame(x, y3, condition) cols <- c("1"="grey80","2"="grey70","3"="grey60","4"="grey50","5"="grey40") ggplot() + geom_bar(aes(fill=condition, y=y3, x=x), data=df2, position="stack", stat="identity", width = 0.5) + # 第一条折线:linetype映射到自定义分类名,可根据业务修改 geom_line(mapping = aes(x = x, y = y1*50, linetype = "指标1"), data=df, size = 1, color = "black") + geom_point(mapping = aes(x = x, y = y1*50), data=df, size = 2, color = "black") + geom_text(aes(x=x, y=y1*50, label = round(y1, 3)), data=df, vjust = "outward", hjust = "outward",show.legend = FALSE, color="black") + # 第二条折线:linetype映射到第二个自定义分类名 geom_line(mapping = aes(x = x, y = y2*50, linetype = "指标2"), data=df, size = 1, color = "black") + geom_point(mapping = aes(x = x, y = y2*50), data=df, size = 2, color = "black") + geom_text(aes(x=x, y=y2*50, label = round(y2, 3)), data=df, vjust = "outward", hjust = "outward",show.legend = FALSE, color="black") + scale_y_continuous(name = "Number of cases", sec.axis = sec_axis(~./50, name = "Percentage")) + scale_x_continuous(breaks = 1:3, labels=c("2008-2011","2012-2015","2016-2019")) + xlab(NULL) + scale_fill_manual(name = "Resection Index",values = cols) + # 新增:手动配置线型图例的名称和对应线型 scale_linetype_manual(name = "折线指标", values = c("指标1" = 1, "指标2" = 2)) + # 可选:让线型图例同时显示点标记,和图中样式一致 guides(linetype = guide_legend(override.aes = list(shape = 16))) + theme_minimal()
关键修改说明
- 将
geom_line的linetype参数从aes()外移到aes()内,赋值自定义分类名,触发图例自动生成 - 新增
scale_linetype_manual()配置,可自行修改图例名称name参数,以及两个分类对应的显示名称 - 额外优化了原代码直接用
df$列名的不规范写法,改用data参数指定数据源,可读性更高
内容的提问来源于stack exchange,提问作者user13538376
相关产品推荐
相关产品推荐

