使用自定义预定义颜色的热图(d3heatmap?)

时间:2017-02-16 23:34:02

标签: r shiny d3heatmap

我有兴趣以热图风格呈现医院指标。我使用闪亮的,所以我喜欢交互式d3heatmap() - 情节的外观和感觉(但我愿意接受替代方案)。

例如,假设我有4家医院和5个指标。我想绘制每个医院每个指标的得分情况,但是,着色不应该取决于指标的实际值,而是取决于单独进行的统计检验(80%的值可能意味着4/5,但也是800 / 1000,在估计的精度方面非常不同),具有以下分组:

  • 高于平均水平
  • 与普通
  • 没有区别
  • 低于平均水平

示例数据(注意实际数字没有意义):

df <- data.frame(Hospital=rep(LETTERS[10:13], each=5), 
                 Indicator=rep(LETTERS[1:5], 4), 
                 Value=sample(1:10, 20, replace=T), 
                 Conclusion=sample(c("above", "not different", "below"), 20, replace=T))
df$colour[df$Conclusion == "above"] <- "green"
df$colour[df$Conclusion == "not different"] <- "grey"
df$colour[df$Conclusion == "below"] <- "red"
df

d3heatmap我得到:

d1 <- dcast(df, Hospital ~ Indicator, value.var = "Value")
row.names(d1) <- paste0("hosp",d1[[1]])
d3heatmap(d1[-1], dendrogram = "none")

(截图) enter image description here 当我将鼠标悬停在它上面时,我得到指标的实际分数,我感兴趣。但是,着色现在基于指标的实际分数,而不是我的数据框中的颜色。

如何在我的示例数据框中使用颜色,同时保留在鼠标悬停在绘图上时可视化指标值的选项?

2 个答案:

答案 0 :(得分:1)

您可以简单地使用数字来编码颜色,然后使用colors参数传递颜色进行解码:

df$colour[df$Conclusion == "above"] <- 1         #green
df$colour[df$Conclusion == "not different"] <- 2 #grey
df$colour[df$Conclusion == "below"] <- 3         #red

d1 <- dcast(df, Hospital ~ Indicator, value.var = "colour")

d3heatmap(d1[-1], dendrogram = "none", colors=c("green", "grey","red"))

enter image description here

答案 1 :(得分:0)

谢谢HubertL!我扩展它以得到确切的答案:

# Cast to get the matric with the values to display when hovering
d1 <- dcast(df, Hospital ~ Indicator, value.var = "Value")
row.names(d1) <- paste0("hosp",d1[[1]])


# Cast to get the matrix with the colours to display
df$colour[df$Conclusion == "above"] <- 1         #green
df$colour[df$Conclusion == "not different"] <- 2 #grey
df$colour[df$Conclusion == "below"] <- 3         #red
df$colour <- as.numeric(df$colour)
d2 <- dcast(df, Hospital ~ Indicator, value.var = "colour")


# Plot heatmap using colours, and refer to the value-matrix in the 'cellnote'
d3heatmap(d2[-1], dendrogram = "none", colors=c("blue", "grey","red"), cellnote = d1[-1])

补充问题:当(在我的情况下)指标名称很长时,有人知道如何扩大边距吗?