使用ggplot2使用facet_wrap绘制值

时间:2013-12-03 13:26:43

标签: r ggplot2

我有一个矩阵:

mat<-matrix(NA, ncol=7,nrow=9) 
mat[,1]<-c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9) 
mat[,2]<-c(2,4,5,6,7,7,7,8,9) 
mat[,3]<-c(2,48,63,72,81,100,100,100,100) 
mat[,4]<-c(1,2,3,3,4,4,5,5,6) 
mat[,5]<-c(1,2,6,7,8,8,9,10,10) 
mat[,6]<-c(1,1,1,2,3,3,4,4,4) 
mat[,7]<-c(1,1,1,3,4,4,4,5,5)

colnames(mat)<-c("facet","A1","A2","B1","B2","C1","C2")

      facet A1  A2 B1 B2 C1 C2
 [1,]   0.1  2   2  1  1  1  1
 [2,]   0.2  4  48  2  2  1  1
 [3,]   0.3  5  63  3  6  1  1
 [4,]   0.4  6  72  3  7  2  3
 [5,]   0.5  7  81  4  8  3  4
 [6,]   0.6  7 100  4  8  3  4
 [7,]   0.7  7 100  5  9  4  4
 [8,]   0.8  8 100  5 10  4  5
 [9,]   0.9  9 100  6 10  4  5

我想创建以下图:

创建由&#34; facet&#34;面对的9个单独的图。 每个图应包含以下内容:

  • 使用点在x轴图A1和A2上的相同位置,即(X = 1,y = A1)和(X = 1,y = A2)
  • 使用点在x轴图B1和B2上的相同位置,即(X = 2,y = B1)和(X = 2,y = B2)
  • 在x轴上的相同位置使用点绘制C1和C2,即(X = 3,y = C1)和(X = 3,y = C2)

如何做到这一点?我理解如何进行刻面,但我正在努力将两个值绘制在x轴上的相同位置并重复每个A,B和C.有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

首先,将矩阵重新整形为长格式的数据框:

library(reshape2)
dat <- melt(as.data.frame(mat), id.vars = "facet")

> head(dat)
#   facet variable value
# 1   0.1       A1     2
# 2   0.2       A1     4
# 3   0.3       A1     5
# 4   0.4       A1     6
# 5   0.5       A1     7
# 6   0.6       A1     7

然后,根据variable列中的信息创建两个变量:

dat2 <- transform(dat, fac = substr(variable, 2, 2),
                       variable = substr(variable, 1, 1))

> head(dat2)
#   facet variable value fac
# 1   0.1        A     2   1
# 2   0.2        A     4   1
# 3   0.3        A     5   1
# 4   0.4        A     6   1
# 5   0.5        A     7   1
# 6   0.6        A     7   1

简介:

library(ggplot2)
ggplot(dat2, aes(x = variable, y = value)) +
  geom_point(aes(colour = fac)) +
  facet_wrap( ~ facet)

enter image description here

答案 1 :(得分:0)

 a <- cbind(mat[, 1], mat[, 2], 1, 1)
 b <- cbind(mat[, 1], mat[, 3], 1, 2)
 c <- cbind(mat[, 1], mat[, 4], 2, 1)
 d <- cbind(mat[, 1], mat[, 5], 2, 2)
 e <- cbind(mat[, 1], mat[, 6], 3, 1)
 f <- cbind(mat[, 1], mat[, 7], 3, 2)

 data <- as.data.frame(rbind(a, b, c, d, e, f))

 colnames(data) <- c("facet", "value", "type", "time")

 data$type <- factor(data$type, labels = c("A", "B", "C"))

 ggplot(data, aes(y = value, x = type, fill = factor(time))) +
        geom_point(aes(color = factor(time)), 
                   position = position_jitter(w = 0.1, h = 0.0))+
        facet_wrap(~facet)

enter image description here