math - 5 months ago 29

R Question

I would like to create some plots with ggplot using faceting. I'm relatively new to ggplot so I'm struggeling setting up the plot. For testing I set up some test data. The actual data is huge and I want first to play around with these toy case. Here is the toy data

`m1 <- matrix(rep(c("Skin","Human"),100),ncol = 2,byrow = T)`

m2 <- matrix(rep(c("Head","Animal"),200),ncol = 2, byrow=T)

m3 <- matrix(rep(c("Skin","Animal"),250), ncol = 2, byrow=T)

y <- rnorm(550,0,1)

x1 <- rnorm(100,0,1)

x2 <- rnorm(200,0,1)

x3 <- rnorm(250,0,1)

m1 <- as.data.frame(cbind(x1,m1))

m2 <- as.data.frame(cbind(x2,m2))

m3 <- as.data.frame(cbind(x3,m3))

colnames(m1) <- c("x1","type","class")

colnames(m2) <- c("x1","type","class")

colnames(m3) <- c("x1","type","class")

data <- as.data.frame(cbind(y,rbind(m1,m2,m3)))

data <- cbind(data,rnorm(550,0,1))

colnames(data) <- c("y","x1","type","class","x2")

data <- data[,c("y","x1","x2","type","class")]

plot(sort(data[1:100,"y"]),sort(data[1:100,"x1"]),col="red")

points(sort(data[1:100,"y"]),sort(data[1:100,"x2"]),col="blue")

I would like to have a plot for all unique pairs of

`c("type","class")`

`x1`

`x2`

`y`

Answer

Based on the plots that your sample code generates, it seems like you want to plot two sets of points `(x1,y)`

and `(x2,y)`

on the same plot, which `ggplot`

is able to handle well. However, `ggplot`

works well with *long* tables rather than *wide* ones.

I've provided one way to achieve your desired outcome. The following steps can be performed after your chunk of code to achieve the desired outcome.

Melt your table wide-to-long make use of

`ggplot`

's in-built functionality. Note that the`color`

argument automatically plots the`x1`

and`x2`

in different colors.`library(reshape2) # Used to melt the table library(ggplot2) # Used to plot data <- melt(data, id.vars = c('type','class','y'), measure.vars = c('x1','x2')) head(data) # type class y variable value # 1 Skin Human 1.3170057 x1 -1.09101346133313 # 2 Skin Human 1.2805021 x1 -0.883308758331181 # 3 Skin Human -0.7620298 x1 0.0800447346341697 # 4 Skin Human 0.2766297 x1 0.589741587886533 # 5 Skin Human -1.8504755 x1 -0.178520217862402 # 6 Skin Human 0.6474738 x1 0.1039386636512 p1 <- ggplot(data, aes(x = as.numeric(value), y = y, color = variable)) print(p1)`

Using

`facet_wrap`

to facet by unique combinations of`type`

and`class`

`faceted <- p1 + facet_wrap(~type + class) print(faceted)`