R:使用 ggplot 时不显示图例

R: legend not showing when using ggplot

我想为情节添加一个图例。但是,没有任何显示。我看过其他类似的问题,但 none 似乎解决了我的问题。

这是代码的那一部分。

ggplot(lm_model, aes(x=year, y=pred_price)) +
  geom_point(color="red") +
  geom_line(color="red") +
  geom_line(aes(x=year, y=real_price)) +
  labs(title="Linear Regression",
       x="Year",
       y="Gas Price") +
  scale_color_manual(labels = c("Predicted", "True Value"))

下面是这段代码的输出结果(没有您看到的图例):

这可以工作但未测试,因为没有共享数据。您需要将颜色语句移动到 aes():

library(ggplot2)
#Data
lm_model <- data.frame(year=2010:2020,
                       pred_price=runif(11,0,75),
                       real_price=runif(11,0,75))
#Code
ggplot(lm_model, aes(x=year, y=pred_price)) +
  geom_point(aes(color="red")) +
  geom_line(aes(color="red")) +
  geom_line(aes(x=year, y=real_price,color='black')) +
  labs(title="Linear Regression",
       x="Year",
       y="Gas Price") +
  scale_color_manual(labels = c("Predicted", "True Value"),
                     values=c('black','red'))+
  labs(color='Price')

输出: