简体   繁体   中英

Problem adding a trendline to a graph in R ggplot2

I tried to use geom_smooth(method = "lm") and it doesn't work...

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")

You need to provide the aesthetics for the geom_smooth as well. Either by including it in the ggplot() or in the 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")

You can avoid repeating section of the code putting it in the 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM