向 R ggplot2 中的图形添加趋势线的问题

Problem adding a trendline to a graph in R ggplot2

我尝试使用 geom_smooth(method = "lm") 但它不起作用...

percentage.no.work <- cleanData %>% group_by(AREA) %>%
  summarise(percentage = mean(ESTIMATED.CITY.UNEMPLOYMENT))

ggplot() +
  geom_point(data=percentage.no.work, aes(x=AREA, y=percentage), alpha=0.6, color="purple", size=2) +
  geom_smooth(method = "lm") +
  theme_minimal() + ggtitle("Percentage Estimated City Unemployment") + 
  ylab("Percentage")

您还需要为 geom_smooth 提供美学。通过将其包含在 ggplot()geom_smooth() 中:

ggplot() +
  geom_point(data=percentage.no.work, aes(x=AREA, y=percentage), alpha=0.6, color="purple", size=2) +
  geom_smooth(aes(x=AREA, y=percentage), method = "lm") +
  theme_minimal() + ggtitle("Percentage Estimated City Unemployment") + 
  ylab("Percentage")

您可以避免将代码的重复部分放在 ggplot()

ggplot(data=percentage.no.work, aes(x=AREA, y=percentage)) +
  geom_point(alpha=0.6, color="purple", size=2) +
  geom_smooth(method = "lm") +
  theme_minimal() + ggtitle("Percentage Estimated City Unemployment") + 
  ylab("Percentage")