绘制矩阵的所有列与矩阵的第一列,绘制在R中

时间:2018-06-18 09:44:05

标签: r ggplot2 r-plotly

我有一个2d矩阵我希望在第一列上绘制列,我可以使用matplot绘制它,有没有办法用plotly做类似的事情,我尝试使用添加它们作为跟踪但它覆盖了没有添加它们的痕迹。

mat <- array(rnorm(10*10*10), dim=c(10, 10, 10))
df <- data.frame( 500*(1:10))
for(i in 3:5){
  for(j in 4:5){
    df <-  cbind(df,mat[1:10,i,j])
  }
}
matplot(x= df[,1], y= as.matrix(df[-1]), type='l')
# plot_ly(y= as.matrix(df[-1]), x= df[,1] ,type="scatter", mode="markers+lines")

1 个答案:

答案 0 :(得分:0)

You need to reshape to long format. Using readable columns names would help.

library(tidyr)
df2 <- df %>% 
  setNames(paste0('V', 1:7)) %>% 
  gather(key, value, -V1)

p <- ggplot(df2, aes(V1, value, color = key)) + geom_line()
plotly::ggplotly(p)

enter image description here

相关问题