bio_r_learner
bio_r_learner

Reputation: 25

data layout for faceting in ggplot

New to R: I have a large data set that I would like to visualize in facets. An example data frame:

Sample <- c("Hair", "Hair", "Hair", "Skin", "Skin", "Skin")
Drug <- c("Vehicle", "Drug1", "Drug2", "Vehicle", "Drug1", "Drug2")
Param1 <- c(2,4,6,2,3,6)
Param2 <- c(10,15,20,10,18,23)
data <- data.frame(Sample,Drug,Param1,Param2)

I can make a faceted image for Param1 with:

ggplot (data, aes(x=Drug, y=Param1)) + geom_point() +facet_grid(.~Sample)

However I would like Param2 to be visualized in the same faceted output. So far I did this by reformatting the data frame as below, however this would be time-consuming for the larger data set that I have:

data2 <- data [,1:2]
data3 <- data2
data2 <- rbind (data2,data3)
Parameter <- c(rep(1,6),rep(2,6))
Combo = c(Param1,Param2)
data2 <- data.frame (data2, Combo, Parameter)
ggplot (data2, aes(x=Drug, y=Combo)) + geom_point() + facet_grid (Parameter~Sample)

Would it be possible to use the data data.frame to achieve the same faceted image that was shown in the plot of data2? Thanks very much for any help or advice!

Upvotes: 1

Views: 97

Answers (1)

Jaap
Jaap

Reputation: 83275

What you are actually trying to do is reshaping your data and them plotting it. Now you have done this manually, but this can be done programmaticaly with the dplyr and tidyr packages:

library(dplyr)
library(tidyr)
data2 <- data %>% gather(Parameter, Combo, c(Param1,Param2))

ggplot(data2, aes(x=Drug, y=Combo, color=Parameter)) +
  geom_point(size=3) +
  facet_grid(Parameter~Sample) +
  theme(axis.title.y=element_blank())

this gives: enter image description here

Instead of the combination of dplyr and tidyr, you can also use the reshape2 package.


As an alternative you can consider the following solution:

ggplot (data, aes(x=Drug, y=Param1)) + 
  geom_point(aes(color="red"), size=3) +
  geom_point(aes(x=Drug, y=Param2, color="blue"), size=3) +
  scale_color_manual("Parameter", values=c("red","blue"), labels=c("Param1","Param2")) +
  facet_grid(.~Sample) +
  theme(axis.title.y=element_blank())

this gives: enter image description here

Upvotes: 1

Related Questions