0

I'm trying to add a regression line to my scatterplot using the following snippet of code


library(ggplot2)
CouncilNames <- c("Antrim and Newtownabbey", "Armagh City, Banbridge and Craigavon", "Causeway Coast and Glens", "Lisburn and Castlereagh", "Mid and East Antrim", "Mid Ulster", "Newry, Mourne and Down")
NumberOfFoodPlaces <- c(110, 170,124, 94, 114, 140, 129)
NumberOfStrayDogs <- c(525, 878, 454, 409, 762, 455, 894)

df <- data.frame(CouncilNames, NumberOfStrayDogs, NumberOfFoodPlaces)
df


plot <- ggplot(df, aes(x=NumberOfFoodPlaces, y=NumberOfStrayDogs, group = CouncilNames, 
                       colour = CouncilNames)) + 
  geom_point() + labs(y="No. of Stray Dogs", x = "No.of Food Establishments") + 
  ggtitle("Correlation between the No. of Stray Dogs and the No.of Food Establishments")
plot

plot + geom_smooth(formula = y ~ x, method = "lm")

cor(df$NumberOfFoodPlaces, df$NumberOfStrayDogs)
test <- cor.test(df$NumberOfFoodPlaces, df$NumberOfStrayDogs)
test


However, the regression line isn't appearing and the only issue I can see is > plot `geom_smooth()` using formula 'y ~ x' is highlighted red in the console. Anyone any ideas?

2
  • 2
    Welcome to stack ! Please, try to give a minimal reproducible example by giving a toy dataset or using dput on your data, see minimal reproducible example Commented Apr 11, 2021 at 22:38
  • Hi @denis! Please see above the amended code of the exact plot I am creating Commented Apr 11, 2021 at 22:51

1 Answer 1

5

The geom_smooth function operates by color and group. Since each color has only a single point, a line cannot be created. Instead, you must move these aesthetics to geom_point so that all of the data is considered by geom_smooth.

ggplot(df, aes(x=NumberOfFoodPlaces, y=NumberOfStrayDogs)) + 
  geom_point(aes(colour = CouncilNames, group = CouncilNames)) +
  labs(y="No. of Stray Dogs", x = "No.of Food Establishments") + 
  ggtitle("Correlation between the No. of Stray Dogs and the No.of Food Establishments") +
  geom_smooth(formula = y ~ x, method = "lm")

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Ah that make's total sense now!! Thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.