Search code examples
rggplot2facet-grid

How to create ggplot with facet_grid() for each column of a matrix


I want to create a plot in R with ggplot() to visualise the data included in variable matrix that looks like this:

matrix <- matrix(c(time =c(1,2,3,4,5),v1=rnorm(5),v2=c(NA,1,0.5,0,0.1)),nrow=5)
colnames(matrix) <- c("time","v1","v2")

df <-data.frame(
  time=rep(matrix[,1],2),
  values=c(matrix[,2],matrix[,3]),
  names=rep(c("v1","v2"), each=length(matrix[,1]))
)
ggplot(df, aes(x=time,y=values,color=names)) +
  geom_point()+
  facet_grid(names~.)

Is there a faster way than transforming the data in a data.frame like I do? This way seems to be very laborious.. I would appreciate every help!! Thanks in advance.


Solution

  • A tidyverse approach:

    This will produce the data structure you need to use in ggplot

    library(tidyverse)
     matrix %>% 
      as_data_frame() %>% 
      gather(., names, value, -time) 
    

    This will generate data structure and plot all at once

    matrix %>% 
      as_data_frame() %>% 
      gather(., names, value, -time) %>% 
      ggplot(., aes(x=time,y=value,color=names)) + 
      geom_point()+
      facet_grid(names~.)