Search code examples
rggplot2line-plot

How to create two lines and scatter plots using ggplot


I have the following data in 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)

I need to create a scatter plot with two straight trendlines for e and f, but I'm lost on how to create that. I found this article: https://sakaluk.wordpress.com/2015/08/27/6-make-it-pretty-plotting-2-way-interactions-with-ggplot2/ which I tried following, but didn't work the way I wanted.

I also tried using melt from reshape2 package, but I can't get the plots to show the way I want to - with two trendlines for e and f in the scatter plot.

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

After this things went downhill. All the codes I tried either have some basic scatter plot with geom_smooth() or just some generic error.

EDIT

The plot should contain scatterplot containing relationship between intial.e and initial.f with a trend line, and another relationship between final.e and final.f with a trend line in the same plot.


Solution

  • How about something like this?

    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)
    

    enter image description here

    Or with points

    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)
    

    enter image description here


    Update

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

    enter image description here

    We're showing a trend-line based on a simple linear regression lm, including confidence band (disable with se = F inside geom_smooth). You could also show a LOESS trend with method = loess inside geom_smooth. See ?geom_smooth for more details.