Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heat map with numbers in ggvis

Tags:

r

ggvis

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 enter image description here

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

enter image description here

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

Any ideas?

like image 657
kismsu Avatar asked Jul 11 '14 15:07

kismsu


People also ask

How to create the heatmap in ggplot2?

We can use the following code to create the heatmap in ggplot2: library (ggplot2) ggplot (melt_mtcars, aes (variable, car)) + geom_tile (aes (fill = value), colour = "white") + scale_fill_gradient (low = "white", high = "red")

What is the format of a heatmap?

The other common form for heatmap data sets it up in a three-column format. Each cell in the heatmap is associated with one row in the data table. The first two columns specify the ‘coordinates’ of the heat map cell, while the third column indicates the cell’s value. Best practices for using a heatmap

How are values encoded in a heatmap?

Values in those columns will be encoded into the heatmap itself. The other common form for heatmap data sets it up in a three-column format. Each cell in the heatmap is associated with one row in the data table. The first two columns specify the ‘coordinates’ of the heat map cell, while the third column indicates the cell’s value.

How is the right side of a heatmap sorted?

The right-side heatmap is sorted by the last column value. A more advanced technique involves grouping and clustering category values by measurement of similarity. This is often seen in the clustered heatmap use case discussed below.


Video Answer


1 Answers

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)
like image 159
wch Avatar answered Sep 21 '22 09:09

wch