![](/img/trans.png)
[英]ggplot2 facet_grid How to create different x-axis with keeping all values in each panel?
[英]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 中轉換數據更快的方法? 這種方式似乎很費力..我將不勝感激! 提前致謝。
一種整潔的方法:
這將生成您需要在 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~.)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.