簡體   English   中英

向 R 繪圖熱圖中添加水平線

[英]Adding horizontal lines to an R plotly heatmap

我正在嘗試將水平線添加到R plotly heatmap中,該heatmap圖將位於 heatmap 的幾行之間。

這是一個示例data.frameheatmap

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")

這使: 在此處輸入圖像描述

現在假設我想在"r2""r3"之間添加一條橫跨整個heatmap的水平線,並在"r4""r5"之間添加一條類似的線。

我不知道對應的y位置應該是什么。

如果我的df$rowinteger/numeric而不是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)

在此處輸入圖像描述

所以我的問題是:

  1. 如果熱圖的行是character ,有沒有辦法在行之間放置水平線?
  2. 有沒有一種更緊湊的方法來添加多條水平線,而不是像我上面的代碼那樣明確地對每一條進行編碼?

我不確定是否可以在因子類的兩個級別之間畫線。

至於您的第二個問題,我們可以使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM