首页 > 解决方案 > 如何根据列值更改线条的颜色

问题描述

我正在尝试使用 ggplot 从数据框中绘制关于仅来自欧洲和美洲的国家的历史预期寿命的图表。我的想法是让所有欧洲国家的线条变成蓝色,美洲变成红色。

这是我的代码:

ggplot(AmericasEuropeData, aes(x = year, y = lifeExp, group = country, color = country)) +
  geom_line(lwd = 1, show.legend = FALSE) + 
  scale_color_manual(values = country_colors) +
  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")

显示下图:

组合图

我尝试更改color = country为,color = continent但它使所有线条变成灰色,而不是每个大陆的不同颜色。我该如何解决这个问题?我知道我可能搞砸了一些非常简单的事情。

AmericasEuropeData数据框预览

数据框

标签: rdataframeggplot2plot

解决方案


正如@AllanCameron 所说color = country,它通过更改color = continent和删除完美地工作。scale_color_manual(values = country_colors)

这是它现在的样子:

最终图像


推荐阅读