在 ggplot2 中添加回归线

时间:2021-04-11 22:35:16

标签: r ggplot2

我正在尝试使用以下代码片段向散点图添加回归线


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


但是,回归线没有出现,我能看到的唯一问题是 > plot `geom_smooth()` using formula 'y ~ x' 在控制台中以红色突出显示。有人有什么想法吗?

1 个答案:

答案 0 :(得分:5)

geom_smooth 函数按颜色和组进行操作。由于每种颜色只有一个点,因此无法创建一条线。相反,您必须将这些美学移至 geom_point,以便 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