如何在R中为2x2x2设计创建ggplot 2意大利面图?

时间:2017-09-24 22:49:59

标签: r 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)
dat01 <- data.frame(climate, place, control, treatment)

我想在一个框架中创建2个不同的意大利面条图,这样它就按地点分类,但两个气候区域都存在于同一个图中(不同的颜色)

这是我的尝试

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)

这会产生一个输出,但这些图似乎没有明显地将控制加入到相应的处理中。一些控制和治疗似乎相互联系。

此外,我无法根据需要生成两个不同的地块。

此外,如果有一种简单的方法可以分别为每个图添加标题,那将会很棒。

1 个答案:

答案 0 :(得分:3)

我认为这就是你想要的:

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

enter image description here