我试图用最佳拟合线和 95% 预测线绘制线性回归,但是在使用stat_smooth或geom_smooth我得到图中看到的图形时。这些线没有显示在图表上,它似乎试图为所有站点制作这些线。数据的模型如下图所示。感谢您的时间和帮助。
Site Cu Fe
A 1 123
B 2 123
C 3 534
D 4 364
E 5 234
F 6 634
G 7 784
H 8 856
Run Code Online (Sandbox Code Playgroud)
您正在尝试使用color=site对一次观察进行回归,这就是为什么您没有返回任何行的原因。
这是预测的 95% 置信区间的最佳拟合线:
library(ggplot2)
# produce data
df1 <- structure(list(Site = c("A", "B", "C", "D", "E", "F", "G", "H"), Cu = 1:8, Fe = c(123L, 123L, 534L, 364L, 234L, 634L, 784L, 856L)), .Names = c("Site", "Cu", "Fe"), row.names = c(NA, -8L), class = "data.frame")
# ordinary case of linear regression with 95CI band
ggplot(data = df1, aes( x = Fe, y = Cu)) +
geom_point() +
geom_smooth(method="lm")
Run Code Online (Sandbox Code Playgroud)
如果您仍然想强制点具有颜色图例,您可以执行以下操作:
# plot regression line with band and color points by Site
ggplot(data = df1, aes( x = Fe, y = Cu)) +
geom_smooth(method="lm") +
geom_point(aes(color=Site))
Run Code Online (Sandbox Code Playgroud)
由于每个站点 [只有一个] 观察,我建议您标记点而不是将 geom_point 映射到颜色:
ggplot(data = df1, aes(x = Fe, y = Cu)) +
geom_smooth(method = "lm") +
geom_label(aes(label=Site))
Run Code Online (Sandbox Code Playgroud)
另一种选择可能是您想为每个站点绘制一条线,并且您的模型数据集不完整,在这种情况下:
df1 <- data.frame( Site = sample(letters[1:8], 999, replace=T),
Fe = runif(999),
Cu = 1:999+rnorm(1))
ggplot(data = df1, aes(x = Fe, y = Cu, colour=Site)) +
geom_smooth(method = "lm", alpha=0.1) +
geom_point(alpha=0)
Run Code Online (Sandbox Code Playgroud)