如何使用facet_grid()为矩阵的每列创建ggplot

如何使用facet_grid()为矩阵的每列创建ggplot,r,ggplot2,facet-grid,R,Ggplot2,Facet Grid,我想用ggplot()在R中创建一个绘图,以可视化变量矩阵中包含的数据,如下所示: 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]),

我想用
ggplot()
在R中创建一个绘图,以可视化变量
矩阵中包含的数据,如下所示:

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~.)
matrixtidyverse方法:

这将生成ggplot中需要使用的数据结构

library(tidyverse)
 matrix %>% 
  as_data_frame() %>% 
  gather(., names, value, -time) 
这将同时生成数据结构和绘图

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