简体   繁体   中英

Adding horizontal lines to an R plotly heatmap

I'm trying to add horizontal lines to an R plotly heatmap that will be located between several of the heatmap 's rows.

Here's an example data.frame and a heatmap :

library(plotly)
set.seed(1)
df <- matrix(rnorm(18), nrow = 6, ncol = 3, dimnames = list(paste0("r",1:6),1:3)) %>%
  reshape2::melt() %>%
  dplyr::rename(row=Var1,col=Var2)
plot_ly(x = df$col, y = df$row,z = df$value,type = "heatmap")

Which gives: 在此处输入图像描述

Now suppose I want to add a horizontal line between "r2" and "r3" that runs across the entire heatmap , and a similar one between "r4" and "r5" .

I don't know what should be the y location the corresponds to that.

I am able to get this done if my df$row s are integer/numeric rather than character :

library(plotly)
set.seed(1)
df <- matrix(rnorm(18), nrow = 6, ncol = 3, dimnames = list(1:6,1:3)) %>%
  reshape2::melt() %>%
  dplyr::rename(row=Var1,col=Var2)
plot_ly(x = df$col, y = df$row,z = df$value,type = "heatmap") %>%
  add_lines(y = 2.5, x = c(min(df$col)-0.5,max(df$col)+0.5), line = list(color = "black",dash = "dot",size = 5),inherit = FALSE,showlegend = FALSE) %>%
  add_lines(y = 4.5, x = c(min(df$col)-0.5,max(df$col)+0.5), line = list(color = "black",dash = "dot",size = 5),inherit = FALSE,showlegend = FALSE)

在此处输入图像描述

So my questions are:

  1. Is there a way to place the horizontal lines between rows if the rows of the heatmap are character ?
  2. Is there a more compact way of adding multiple horizontal lines rather than explicitly having to code each one, as in my code above?

I am not sure if it would be possible to draw lines between two levels of a factor class.

As for your second question, we can use add_segments :

library(plotly)

set.seed(1)

df <- matrix(rnorm(18), nrow = 6, ncol = 3, dimnames = list(1:6,1:3)) %>%
  reshape2::melt() %>%
  dplyr::rename(row=Var1,col=Var2)


hdf <- data.frame(y1 = c(2.5, 4.5), 
                  x1 = rep(min(df$col)-0.5, 2), x2 = rep(max(df$col)+0.5, 2))

plot_ly(x = df$col, y = df$row,z = df$value,type = "heatmap") %>%
  add_segments(data =hdf , y=~y1, yend =~y1, x=~x1, xend =~x2,
               line = list(color = "black",dash = "dot",size = 5), 
               inherit = FALSE,showlegend = FALSE)

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