Reputation: 6399
I have a matrix:
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
I would like to create the following plot:
Create 9 separate plots faceted by "facet". Each plot should contain the following:
How can this be done? I understand how to do faceting but I'm struggling with plotting the two values in the same position on the x axis and repeating for each A,B and C. can someone help?
Upvotes: 0
Views: 340
Reputation: 560
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)
Upvotes: 0
Reputation: 81683
First, reshape your matrix to a data frame in the long format:
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
Then, create two variables based on the information in the column 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
Plot:
library(ggplot2)
ggplot(dat2, aes(x = variable, y = value)) +
geom_point(aes(colour = fac)) +
facet_wrap( ~ facet)
Upvotes: 1