R语言使用ggplot2绘制折线图时图例不显示如何解决
图例不显示的核心原因
你的代码犯了ggplot2最容易踩的映射覆盖错误:在geom_line()的aes()映射外部额外指定了固定color参数,直接覆盖了aes内部写的颜色分组映射,ggplot无法识别到分组逻辑,自然不会生成图例。
看你写的两个几何图层:
- 绘制印度折线时,先在aes里写了
color = "India"做分组映射,转头就在aes外面加了color="#339999"写死颜色 - 绘制中国折线时同理,aes里写了
color = "China",外面又加了color="#993333"
aes外部写的固定样式参数优先级远高于内部映射,你相当于手动告诉ggplot“这两条线的颜色我直接指定,不需要按分组映射”,后面写的scale_colour_manual()根本接收不到分组数据,图例当然出不来。你之前试过删掉scale_colour_manual让系统自动生成图例也失败,也是同一个原因——映射都被覆盖了,不管用不用手动标度都出不来图例。
你之前运行代码得到的无图例效果如下:
最小修改方案
不用改整体结构,只需要把两个geom_line()里aes外部的固定color参数删掉,颜色规则全部交给标度函数控制就行,改完的代码如下:
country_data %>% ggplot(aes(x = Year)) + geom_line(data = country_data_india, mapping=aes(y = as.numeric(TotPop1Jan), color = "印度"), size=1.25) + geom_line(data = country_data_china, mapping=aes(y = as.numeric(TotPop1Jan), color = "中国"), size=1.25) + theme_minimal() + labs(y="总人口(单位:千人)", title="1950-2021年中国与印度人口变化", subtitle="联合国经济和社会事务部人口司(2022).\n《世界人口展望2022》在线版.\n© Jeroen De Ryck")+ theme(plot.subtitle = element_text(size = 8, colour ="darkgrey"), axis.line = element_line(colour = "black"), axis.ticks = element_line(linetype=1), axis.ticks.x = element_line()) + scale_x_continuous(breaks = seq(1950,2021,5)) + scale_y_continuous(breaks = seq(300000, 1500001, 200000)) + scale_colour_manual(name = "国家", values=c("印度"="#339999", "中国"="#993333"))
运行后图表右侧就会正常显示对应两个国家颜色的图例。
更简洁的规范写法
你现在拆分两个数据集、写两个geom_line的写法冗余度很高,建议先把两份数据合并为长表,用一个geom_line完成绘图,从根源上避免映射冲突:
library(dplyr) plot_df <- bind_rows( country_data_india %>% transmute(Year, TotPop1Jan = as.numeric(TotPop1Jan), 国家 = "印度"), country_data_china %>% transmute(Year, TotPop1Jan = as.numeric(TotPop1Jan), 国家 = "中国") ) ggplot(plot_df, aes(x = Year, y = TotPop1Jan, color = 国家)) + geom_line(size = 1.25) + theme_minimal() + labs(y="总人口(单位:千人)", title="1950-2021年中国与印度人口变化", subtitle="联合国经济和社会事务部人口司(2022).\n《世界人口展望2022》在线版.\n© Jeroen De Ryck")+ theme(plot.subtitle = element_text(size = 8, colour ="darkgrey"), axis.line = element_line(colour = "black"), axis.ticks = element_line(linetype=1), axis.ticks.x = element_line()) + scale_x_continuous(breaks = seq(1950,2021,5)) + scale_y_continuous(breaks = seq(300000, 1500001, 200000)) + scale_colour_manual(values=c("印度"="#339999", "中国"="#993333"))
其他容易导致图例消失的常见问题
- 在
theme()中误设置legend.position = "none",会直接全局隐藏图例 - 所有和分组相关的属性(颜色、线型、形状等)都写在
aes()外部,ggplot不会识别为分组变量,不会触发生成图例 - 手动标度(比如
scale_colour_manual)中设置的breaks值和实际映射的分组值完全不匹配,会导致图例无法渲染 - 给几何图层单独设置
show.legend = FALSE,会强制隐藏该图层对应的图例
内容的提问来源于stack exchange,提问作者DagelijksGamer
相关产品推荐
相关产品推荐


