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'
在控制台中以红色突出显示。有人有什么想法吗?
解决方案
该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")
推荐阅读
- java - 在arraylists java中组合值的问题
- python - 为什么当我在 Python 中写 "u"==("a" or "e" or "i" or "o" or "u") 时我得到 False?“a”或“e”或“i”或“o”或“u”中的“u”不是吗?
- latex - \printbibliography 未显示参考文献列表
- asp.net - 仅选择一列 linq lambda query asp.net
- javascript - 将公式从 JavaScript 添加到 CSV 以导入到 Google 表格会导致多列
- react-native - React Native Paper Text Input - 在初始状态下调整标签颜色
- python - 错误“OSError:告诉位置被 next() 调用禁用”
- python-3.x - Django Python POST方法不写入数据库
- python - ValueError:无法将字符串转换为浮点数:Sklearn 和 pandas 中的错误
- javascript - 如何使用一个组件来渲染一组值