Heat map with numbers in ggvis

∥☆過路亽.° 提交于 2019-11-29 14:07:46

问题


I'm trying to replicate the heat map with numbers from ggplot2 in ggvis. ggplot2 version is

library(ggplot2)
hec <- as.data.frame(xtabs(Freq ~ Hair + Eye, HairEyeColor))
ggplot(hec, aes(Hair, Eye)) +
geom_tile(aes(fill = Freq)) + 
geom_text(aes(label = Freq),colour="white") 

and it looks like that

My version in ggvis is

hec%>%
ggvis(~Hair, ~Eye, fill=~Freq)%>%
layer_rects(width = band(), height = band()) %>%
layer_text(text:=~Freq,fontSize := 20, fill:="white",baseline:="top",align:="center") %>%
scale_nominal("x", padding = 0, points = FALSE) %>%
scale_nominal("y", padding = 0, points = FALSE) 

and the result is not perfect

I've tried to fix numbers align by manually adding margins, but this case is not resizeable.

Any ideas?


回答1:


One workaround is to use xcenter and ycenter scales:

hec <- as.data.frame(xtabs(Freq ~ Hair + Eye, HairEyeColor))

hec%>%
  ggvis(~Hair, ~Eye, fill=~Freq) %>%
  layer_rects(width = band(), height = band()) %>%
  layer_text(
    x = prop("x", ~Hair, scale = "xcenter"),
    y = prop("y", ~Eye, scale = "ycenter"),
    text:=~Freq, fontSize := 20, fill:="white", baseline:="middle", align:="center") %>%
  scale_nominal("x", padding = 0, points = FALSE) %>%
  scale_nominal("y", padding = 0, points = FALSE) %>% 
  scale_nominal("x", name = "xcenter", padding = 1, points = TRUE) %>%
  scale_nominal("y", name = "ycenter", padding = 1, points = TRUE)



回答2:


In layer_text(), try align:="left". That seemed to work in this example.



来源:https://stackoverflow.com/questions/24701419/heat-map-with-numbers-in-ggvis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!