在 R 中绘制矩阵的所有列和矩阵的第一列
Plot all the colums of matrix vs first column of matrix with plotly in R
我有一个二维矩阵,我希望针对第一列按列绘制,我可以使用 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")
您需要重新整形为长格式。使用可读的列名称会有所帮助。
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)
我有一个二维矩阵,我希望针对第一列按列绘制,我可以使用 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")
您需要重新整形为长格式。使用可读的列名称会有所帮助。
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)