[英]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:我想用
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~.)
Is there a faster way than transforming the data in a data.frame like I do?有没有比像我一样在 data.frame 中转换数据更快的方法? This way seems to be very laborious.. I would appreciate every help!!
这种方式似乎很费力..我将不胜感激! Thanks in advance.
提前致谢。
A tidyverse approach:一种整洁的方法:
This will produce the data structure you need to use in ggplot这将生成您需要在 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~.)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.