如何使用 ggplot 创建两条线和散点图

How to create two lines and scatter plots using ggplot

我在 R 中有以下数据:

id <- factor(seq(1:72))
initial.e <- rnorm(n=72, mean = 21.51, sd = 6.58)
initial.f <- rnorm(n = 72, mean = 20.75, sd = 3.378)

final.e <- rnorm(n = 72, mean = 19.81, sd = 7.48)
final.f <- rnorm(n = 72, mean = 19.77, sd = 5.389)

data <- data.frame(id,initial.e, initial.f, final.e, final.f)

我需要为 ef 创建一个带有两条直线趋势线的散点图,但我不知道如何创建它。我找到了这篇文章:https://sakaluk.wordpress.com/2015/08/27/6-make-it-pretty-plotting-2-way-interactions-with-ggplot2/,我尝试关注它,但没有按照我想要的方式工作。

我也尝试使用 reshape2 包中的 melt,但我无法让图表显示我想要的方式 - e 和 [= 有两条趋势线13=] 在散点图中。

datamelt <- melt(data, id = 'id')
datamelt <- datamelt %>% mutate(names = ifelse(datamelt$variable %in% c('initial.e', 'initial.f'), 'Before', 'After'))

datamelt <- datamelt %>% mutate(types = ifelse(datamelt$variable %in% c('final.e', 'final.f'), 'e', 'f'))

在这之后事情就开始走下坡路了。我尝试的所有代码要么有一些带有 geom_smooth() 的基本散点图,要么只是一些一般错误。

编辑

该图应包含散点图,其中包含 intial.einitial.f 之间的关系以及趋势线,以及 final.efinal.f 之间的另一个关系以及趋势线相同的情节。

这样的怎么样?

data %>%
    gather(k, value, -id) %>%
    mutate(
        state = gsub("(\.e$|\.f$)", "", k),
        what = gsub("(initial\.|final\.)", "", k)) %>%
    ggplot(aes(id, value, colour = what)) +
    geom_line() +
    facet_wrap(~ state)

或带积分

data %>%
    gather(k, value, -id) %>%
    mutate(
        state = gsub("(\.e$|\.f$)", "", k),
        what = gsub("(initial\.|final\.)", "", k)) %>%
    ggplot(aes(id, value, colour = what)) +
    geom_line() +
    geom_point() + 
    facet_wrap(~ state)


更新

data %>%
    gather(k, value, -id) %>%
    mutate(
        state = gsub("(\.e$|\.f$)", "", k),
        what = gsub("(initial\.|final\.)", "", k)) %>%
    select(-k) %>%
    spread(state, value) %>%
    ggplot(aes(x = initial, y = final, colour = what, fill = what)) +
    geom_smooth(fullrange = T, method = "lm") +
    geom_point()

我们显示的是基于简单线性回归 lm 的趋势线,包括置信带(在 geom_smooth 内使用 se = F 禁用)。您还可以在 geom_smooth 内显示 method = loess 的 LOESS 趋势。有关详细信息,请参阅 ?geom_smooth

我想你要找的是这样的东西:我没有测试代码,但它应该给你一个想法

ggplot(data) + 
  geom_point(aes(x=initial.e, y=initial.f)) +
  geom_smooth(method = "lm", se = FALSE, aes(initial.e, final.e)) + 
  geom_point(aes(x=final.e, y = final.f)) +
  geom_smooth(method = "lm", se = FALSE, aes(final.e, final.f))