如何在ggplot中为每个data.frame放置相关线

How to place correlation line for each data.frame in ggplot

我不知道如何在 R 中为每个 data.frame 放置两条相关线。代码如下:

combinedplot <- ggplot() +
geom_point(data = data.frame1, aes(x=variable1, y=variable2, color='red')) + 
geom_point(data = data.frame2, aes(x=variable1, y=variable2, color='blue')) +
labs(x="Date", y="PM 2.5 ugm3")
combinedplot

我也试过了

combinedplot <- ggplot() +
geom_point(data = data.frame1, aes(x=variable1, y=variable2, color='red')) + 
geom_point(data = data.frame2, aes(x=variable1, y=variable2, color='blue')) +
labs(x="Date", y="PM 2.5 ugm3")
combinedplot + geom_smooth(method='lm')

combinedplot <- ggplot() +
geom_point(data = data.frame1, aes(x=variable1, y=variable2, color='red')) + 
geom_smooth(method='lm') +
geom_point(data = data.frame2, aes(x=variable1, y=variable2, color='blue')) + 
geom_smooth(method='lm') +
labs(x="Date", y="PM 2.5 ugm3")
combinedplot 

这两个选项都只打印没有线条的图表,有什么建议吗?

您需要向geom_smooth()函数提供数据和美学,例如:

+ geom_smooth(
  data = data.frame1,
  aes(x = variable1, y = variable2, color = "red"),
  method = "lm"
)

如果你想合并这两个图,最好在 data.frames 之前合并这两个,rbind 在定义一个新变量后将它们合并在一起,该变量告诉 data.frame 数据是什么来自。

类似下面的内容。

library(ggplot2)

data.frame1$group <- "df1"
data.frame2$group <- "df2"
df_all <- rbind(data.frame1[, c("variable1", "variable2", "group")],
                data.frame2[, c("variable1", "variable2", "group")])


combinedplot <- ggplot(df_all, aes(x = variable1, y = variable2, colour = group)) +
  geom_point() + 
  labs(x = "Date", y = "PM 2.5 ugm3") +
  scale_color_manual(values = c('red', 'blue'))

combinedplot + geom_smooth(method = 'lm')

数据创建代码。

set.seed(1234)    # Make the results reproducible
data.frame1 <- data.frame(variable1 = 1:20, variable2 = 2*(1:20) + rnorm(20) )
data.frame2 <- data.frame(variable1 = 1:25, variable2 = 0.75*(1:25) + rnorm(25) )