我正在尝试将回归线添加到我的 ggplot 中。下面是我用来制作绘图的代码。我想在第一个图(L5andDownTempAvgPlot)中绘制回归线,但不断遇到以下错误。我还想知道是否有一种方法可以得到 ggplot 中两条线的最佳拟合线(来自 DailyAvgL5 和 DailyDownGaugeAvg 的线)。我不确定这是否可能,但如果可以的话,这就是我最终希望能够做到的。
#create plot of daily avgs
library(ggplot)
library(dplyr)
L5andDownTempAvgPlot <- (ggplot(NULL, aes(Date, mean_temp)) +
geom_line(data = DailyAvgL5, color = "black") +
geom_line(data = DailyDownGaugeAvg, color = "red") +
geom_smooth(data = DailyDownGaugeAvg, method = 'lm', formula = DailyDownGaugeAvg$Date~DailyDownGaugeAvg$mean_temp)
)
DownGaugeHeightAvgPlot <- (ggplot(DailyDownGaugeAvg, aes(Date, DailyGaugeHeightAvg)) +
geom_line(data = DailyDownGaugeAvg, color = "blue") +
geom_smooth(method = 'lm')
)
DownGaugeHeightAvgPlot + L5andDownTempAvgPlot
`geom_smooth()` using formula = 'y ~ x'
Warning message:
Failed to fit group -1.
Caused by error in `Ops.Date()`:
! * not defined for "Date" objects
dput(head(DailyDownGaugeAvg))
structure(list(Date = structure(c(19789, 19790, 19791, 19792,
19793, 19794), class = "Date"), mean_temp = c(7.94, 8.465625,
7.965625, 7.64673913043478, 8.63645833333333, 9.146875), DailyGaugeHeightAvg = c(15.5787368421053,
12.3515625, 9.34770833333333, 12.2685869565217, 15.6577083333333,
16.4609375)), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))
> dput(head(DailyAvgL5))
structure(list(Date = structure(c(19791, 19792, 19793, 19794,
19795, 19796), class = "Date"), mean_temp = c(9.98765502929687,
9.884833984375, 8.01781209309896, 8.70198394775391, 9.21991678873698,
9.69807739257812)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
我认为这与我试图将回归线拟合到 ggplot (data,...) 中第一个参数中未详细说明的数据有关,但老实说不确定。我对 r 很陌生,所以我问了很多问题,但我很感谢您的帮助。我也无法显示下游仪表mean_temp 和L5mean_temp 之间的相关性,但我相信这超出了这个范围。谢谢。
对于公式,不要使用数据框中的值
# this will fail
ggplot(data)+
geom_smooth(
aes(x = Date, y = mean_temp.x),
method = 'lm',
formula = data$Date ~ data$mean_temp.x,
se = TRUE)
# this works
ggplot(data)+
geom_smooth(
aes(x = Date, y = mean_temp.x),
method = 'lm',
formula = y ~ x,
se = TRUE)
# this works too
ggplot(data)+
geom_smooth(
aes(x = Date, y = mean_temp.x),
method = 'lm',
formula = y ~ poly(x, 2),
se = TRUE)
# so does this
ggplot(data)+
geom_smooth(
aes(x = Date, y = mean_temp.x),
method = 'lm',
formula = y ~ log(x),
se = TRUE)