【问题标题】:Discrete colorbar in R plotlyR中的离散颜色条
【发布时间】:2018-04-19 15:26:43
【问题描述】:

我正在尝试用 R 绘制热图。这是可重现的示例:

test <- structure(list(s1 = c(0L, 0L, 1L, 0L, 1L, 1L), s2 = c(1L, 1L, 
0L, 1L, 0L, 0L), s3 = c(0L, 0L, 0L, 0L, 0L, 0L), s4 = c(0L, 0L, 
0L, 0L, 0L, 0L), s5 = c(0L, 0L, 0L, 0L, 0L, 0L), s6 = c(0L, 0L, 
0L, 0L, 0L, 0L)), .Names = c("s1", "s2", "s3", "s4", "s5", "s6"
), row.names = c("5HT2 type receptor mediated signaling pathway", 
"5HT3 type receptor mediated signaling pathway", "5-Hydroxytryptamine degredation", 
"Alpha adrenergic receptor signaling pathway", "Alzheimer disease-amyloid secretase pathway", 
"Angiogenesis"), class = "data.frame")

以及在 plotly 中生成热图的代码:

f1 <- list(
    family = "Arial, sans-serif",
    size = 5,
    color = "lightgrey")

f2 <- list(
    family = "Old Standard TT, serif",
    size = 10,
    color = "black")

a <- list(
  title = "",
  titlefont = f1,
  showticklabels = TRUE,
  tickangle = 45,
  tickfont = f2,
  exponentformat = "E")

plot_ly(z = as.matrix(test), 
        zmin=0, 
        zmax=1,
        x = colnames(test), 
        xgap = 2, 
        y = rownames(test), 
        ygap =2, 
        type = "heatmap", 
        colorbar=list(ypad = 30, tickmode="array", tickvals = c(0,1), color = 2, autocolorscale = F )) %>% 
  layout(xaxis = a,
         margin = list(l =500, r = 10, b = 200, t = 10))

如您所见,生成的绘图具有连续的比例。我发现了这个StackOverflow question,作者在其中提出了类似的问题。我试图复制答案提供的解决方案,但我无法深入了解它。你能告诉我如何将比例设置为离散而不是连续颜色吗?

谢谢

EDIT1:添加了“a”变量定义

【问题讨论】:

  • 请在layout(xaxis = a, ...中定义a
  • @MarcoSandri 在主要问题中添加,感谢您指出!

标签: r scale plotly heatmap


【解决方案1】:

您需要按如下方式定义色标:

colorScale <- data.frame(z=c(0,0.5,0.5,1),col=c("#440053","#440053","#FDE624","#FDE624"))
colorScale$col <- as.character(colorScale$col)

plot_ly(z = as.matrix(test), 
        x = colnames(test), 
        xgap = 2, 
        y = rownames(test), 
        ygap =2, 
        type = "heatmap", 
        colorscale=colorScale ,
        colorbar=list(ypad = 30, tickvals=c(0.25,0.75), ticktext=c(0,1))) %>% 
  layout(xaxis = a,
         margin = list(l =500, r = 10, b = 200, t = 10))

【讨论】:

  • 感谢您的回答!您能否详细说明您的答案,以便我了解您的所作所为?谢谢!
  • @Law 色标是具有数字列和字符列的数据框。数字列定义值的范围,字符列定义相应范围的颜色。我定义了两个范围:从 0 到 0.5 的紫色和从 0.5 到 1 的黄色。然后应使用colorscale 参数将定义的色标传递给plot_ly
【解决方案2】:

Macro Sandris 的回答非常完美,而且效果很好。

我只想补充一点,如果你需要两个以上的类,你可以使用下面的例子:

2 类(见 Marcos 答案)

colorScale <- data.frame(z=c(0,0.5,0.5,1),col=c("#440053","#440053","#FDE624","#FDE624"))

3 类

colorScale <- data.frame(z=c(0,0.33,0.33,0.66,0.66,1),col=c("#440053","#440053","#FDE624","#FDE624","#DDE431","#DDE431"))

等等。确保传入数据框的向量始终介于 0 到 1 之间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2016-04-07
    • 1970-01-01
    • 2019-04-21
    相关资源
    最近更新 更多