r语言 - 如何用 facet_grid() 为矩阵的每一列创建 ggplot



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

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~.)

有没有比像我一样在数据帧中转换数据更快的方法?这种方式似乎很费力。我将不胜感激每一个帮助!!提前谢谢。

一个整洁的方法:

这将产生您需要在 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~.)

最新更新