如何根据列值更改线条的颜色
How to change color of lines depending on column value
我正在尝试使用 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
数据帧的预览
如@AllanCameron 所说,将 color = country
更改为 color = continent
并删除 scale_color_manual(values = country_colors)
,效果非常好。
这是现在的样子:
我正在尝试使用 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
数据帧的预览
如@AllanCameron 所说,将 color = country
更改为 color = continent
并删除 scale_color_manual(values = country_colors)
,效果非常好。
这是现在的样子: