在 R 中使用 ggplot2 和图例不会出现在我的图中。这是为什么?
Using ggplot2 in R and a legend will not show up in my figure. Why is that?
View(PV)
library(ggplot2)
ssplot <- ggplot(PV, aes(x=year)) + geom_line(aes(y = infinite_horizon), color = "darkred", size = 1) + geom_line(aes(y = through_year_75), color="steelblue", size = 1)
print(ssplot + labs(y="Present Value ($, trillions)", x = "Year") + ggtitle("Measures of Unfunded Social Security Obligations, 2003-2020"))
不幸的是,我还不能 post 图片,但我得到了一个有两条线且没有图例的图形。为什么会这样?任何帮助,将不胜感激。谢谢。
如果没有看到您的数据示例,很难知道,但像下面这样重构您的代码将有助于解决问题:
library(ggplot2)
ssplot <- ggplot(PV, aes(x=year)) +
geom_line(aes(y = infinite_horizon), color = "darkred", size = 1) +
geom_line(aes(y = through_year_75), color="steelblue", size = 1) +
labs(y="Present Value ($, trillions)", x = "Year") +
ggtitle("Measures of Unfunded Social Security Obligations, 2003-2020")
ssplot
在aes()
中设置颜色,使用scale_color_manual()
手动设置颜色
ggplot(PV, aes(x = year)) +
geom_line(aes(y = infinite_horizon, color = "darkred"), size = 1) +
geom_line(aes(y = through_year_75, color="steelblue"), size = 1) +
scale_color_manual(values = c("steelblue" = "steelblue", "darkred" = "darkred"))
View(PV)
library(ggplot2)
ssplot <- ggplot(PV, aes(x=year)) + geom_line(aes(y = infinite_horizon), color = "darkred", size = 1) + geom_line(aes(y = through_year_75), color="steelblue", size = 1)
print(ssplot + labs(y="Present Value ($, trillions)", x = "Year") + ggtitle("Measures of Unfunded Social Security Obligations, 2003-2020"))
不幸的是,我还不能 post 图片,但我得到了一个有两条线且没有图例的图形。为什么会这样?任何帮助,将不胜感激。谢谢。
如果没有看到您的数据示例,很难知道,但像下面这样重构您的代码将有助于解决问题:
library(ggplot2)
ssplot <- ggplot(PV, aes(x=year)) +
geom_line(aes(y = infinite_horizon), color = "darkred", size = 1) +
geom_line(aes(y = through_year_75), color="steelblue", size = 1) +
labs(y="Present Value ($, trillions)", x = "Year") +
ggtitle("Measures of Unfunded Social Security Obligations, 2003-2020")
ssplot
在aes()
中设置颜色,使用scale_color_manual()
手动设置颜色
ggplot(PV, aes(x = year)) +
geom_line(aes(y = infinite_horizon, color = "darkred"), size = 1) +
geom_line(aes(y = through_year_75, color="steelblue"), size = 1) +
scale_color_manual(values = c("steelblue" = "steelblue", "darkred" = "darkred"))