如何使用 facet_grid() 为矩阵的每一列创建 ggplot
How to create ggplot with facet_grid() for each column of a matrix
我想用 ggplot()
在 R 中创建一个图来可视化变量 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~.)
有没有比像我这样在 data.frame 中转换数据更快的方法?这种方式好像很费力。。
我将不胜感激!提前致谢。
一种 tidyverse 方法:
这将生成您需要在 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~.)
我想用 ggplot()
在 R 中创建一个图来可视化变量 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~.)
有没有比像我这样在 data.frame 中转换数据更快的方法?这种方式好像很费力。。 我将不胜感激!提前致谢。
一种 tidyverse 方法:
这将生成您需要在 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~.)