简体   繁体   中英

How to create a ggplot 2 spaghetti plot for a 2x2x2 design in R?

I have data that looks like this

climate <- c("Dry","Wet","Dry","Wet","Dry","Wet","Dry","Wet")
place <- c("Urban", "Urban","Urban","Urban","Rural","Rural","Rural","Rural")
control <- c(4,5,1,0,0,5,6,7)
treatment <- c(1,2,3,0,1,9,9,1)
dat01 <- data.frame(climate, place, control, treatment)

I want to create 2 different spaghetti plots in one frame, such that it is classified by place, but both the climatic regions are present in the same plot (different colors)

Here is my attempt

library(ggvis)
library(gridExtra)
library(reshape)
library(ggplot2)

dat01 <- melt(dat01, id = c("climate","place"))

mytheme <- theme_classic() %+replace% 
    theme(axis.title.x = element_blank(), 
          axis.title.y = element_text(face = "bold", angle = 90))

ggplot(data = dat01, aes(x = variable, y = value, group = place, colour = climate)) +
    mytheme +
    labs(list(x = paste("Plots"), y = paste("Number of Seedlings"))) + 
    geom_line(size = 1)

This produces an output, but the plots do not seem to distinctly join the control to the corresponding treatment. Several of controls and treatments appear to be connected with one another.

Moreover, I am unable to produce two different plots as required.

Also, it would be great if there was an easy way to add titles for each of the plots separately.

I think this is what you want:

library(reshape)
library(ggplot2)

climate <- c("Dry","Wet","Dry","Wet","Dry","Wet","Dry","Wet")
place <- c("Urban", "Urban","Urban","Urban","Rural","Rural","Rural","Rural")
control <- c(4,5,1,0,0,5,6,7)
treatment <- c(1,2,3,0,1,9,9,1)
pair_id <- 1:8
dat01 <- data.frame(climate, place, control, treatment, pair_id)

dat01 <- melt(dat01, id = c("climate","place", "pair_id"))


ggplot(data = dat01, aes(x = variable, y = value, group = pair_id, colour = climate)) +
  facet_wrap(~place)+
  labs(list(x = paste("Plots"), y = paste("Number of Seedlings"))) + 
  geom_line(size = 1) + theme_bw()

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM