Home > Net >  Problem adding a trendline to a graph in R ggplot2
Problem adding a trendline to a graph in R ggplot2

Time:06-01

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

CodePudding user response:

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