如何在ggplot中根据大洲列的取值修改折线的颜色
问题原因
你修改映射后出现全灰折线的核心问题是scale_color_manual的赋值对象不匹配:
你原来的country_colors是和country变量一一对应的颜色向量,当你把aes里的color映射从country改成continent后,ggplot找不到和continent两个取值对应的颜色规则,就会默认输出灰色。
解决方法
只需要修改scale_color_manual的取值,直接给两个大洲指定对应颜色即可,同时要保留group = country的设置(保证每个国家单独生成一条折线)。
修改后的完整代码如下:
ggplot(AmericasEuropeData, aes(x = year, y = lifeExp, group = country, color = continent)) + geom_line(lwd = 1, show.legend = FALSE) + # 替换原来的country_colors,直接给大洲指定颜色 scale_color_manual(values = c("Europe" = "blue", "Americas" = "red")) + theme_bw() + theme(strip.text = element_text(size = rel(1.1))) + ggtitle("Americas + Europe") + geom_vline(xintercept=2020, linetype="dashed") + ylab("Life Expectancy") + xlab("Year")
如果你的continent列里美洲的取值是America而不是Americas,对应修改scale_color_manual里的键名即可。
内容的提问来源于stack exchange,提问作者Coco Garazzo
相关产品推荐
相关产品推荐

