简体   繁体   中英

Plot heatmaps of multiple data frames using a slider in R

I have multiple data.frames and each one of them represent the pairwise interactions of individuals at different time points.

Here is an example of how my data.frames look.

df1 <- matrix(data = rexp(9, rate = 10), nrow = 3, ncol = 3)
df2 <- matrix(data = rexp(16, rate = 10), nrow = 4, ncol = 4)
df3 <- matrix(data = rexp(4, rate = 10), nrow = 2, ncol = 2)

I would like to plot them as it is pointed in this page ( https://plotly.com/r/sliders/ ) where with a slider I can move from one heatmap to the other.

I have tried so far with plotly but I have not succeeded. Any help is highly appreciated.

I am struggling for long with this issue. I might be a bit blind at this point so please forgive me if the question is stupid.

Following the Sine Wave Slider example on https://plotly.com/r/sliders/ this can be achieved like so. The first step of my approach involves converting the matrices to dataframes with columns x, y, z. Second instead of lines we plot heatmaps.

df1 <- matrix(data = rexp(9, rate = 10), nrow = 3, ncol = 3)
df2 <- matrix(data = rexp(16, rate = 10), nrow = 4, ncol = 4)
df3 <- matrix(data = rexp(4, rate = 10), nrow = 2, ncol = 2)

library(tibble)
library(tidyr)
library(plotly)

# Make dataframes
d <- lapply(list(df1, df2, df3), function(d) {
            d %>%
              as_tibble(.colnames = seq(ncol(.))) %>% 
              rowid_to_column("x") %>% 
              pivot_longer(-x, names_to = "y", values_to = "z") %>% 
              mutate(y = stringr::str_extract(y, "\\d"),
                     y = as.numeric(y))
    })

aval <- list()
for(step in seq_along(d)){
  aval[[step]] <-list(visible = FALSE,
                      name = paste0('v = ', step),
                      x = d[[step]]$x,
                      y = d[[step]]$y,
                      z = d[[step]]$z)
}
aval[1][[1]]$visible = TRUE

steps <- list()
fig <- plot_ly()

for (i in seq_along(aval)) {
  fig <- add_trace(fig, x = aval[i][[1]]$x, y = aval[i][[1]]$y, z = aval[i][[1]]$z, visible = aval[i][[1]]$visible, 
                   name = aval[i][[1]]$name, type = "heatmap")
  fig
  step <- list(args = list('visible', rep(FALSE, length(aval))), method = 'restyle')
  
  step$args[[2]][i] = TRUE  
  steps[[i]] = step
}

fig <- fig %>%
  layout(sliders = list(list(active = 0,
                             currentvalue = list(prefix = "Heatmap: "),
                             steps = steps)))
fig

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM