使用geom_smooth或stat_smooth进行绘图

时间:2017-03-07 00:54:39

标签: r ggplot2

我正在尝试使用最佳拟合线和95%预测线绘制线性回归,但在使用stat_smoothgeom_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

截图: enter image description here

1 个答案:

答案 0 :(得分:3)

您尝试使用 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")

enter image description here

如果你仍想强制点有颜色图例,你可以这样做:

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

enter image description here

由于每个站点只有[一个]观察,我建议您标记点而不是将geom_point映射到颜色:

ggplot(data = df1, aes(x = Fe, y = Cu)) +
   geom_smooth(method = "lm") +
   geom_label(aes(label=Site))

enter image description here

另一种选择可能是您希望为每个网站绘制一条线,并且您的模型数据集不完整,在这种情况下:

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)

enter image description here