Adding zero values where none exists for geom_tile

511 Views Asked by At

I'm trying to create a heat map with geom_tile but not all have coordinates have values. Therefore my geom_tile looks like this: enter image description here

The code to create the image is

library(dplyr)
data(mpg)
mydata <- mpg %>% group_by(manufacturer, cyl) %>% summarize(count=n())

mydata %>% ggplot(aes(x=manufacturer, y=cyl, fill=count))+geom_tile()+geom_text(aes(label=count))
1

There are 1 best solutions below

0
On BEST ANSWER

Use complete to fill in the missing sequence :

library(tidyverse)

mpg %>%
  count(manufacturer, cyl, name = 'count')  %>%
  complete(manufacturer, cyl = seq(min(cyl), max(cyl)), 
           fill = list(count = 0)) %>%
  ggplot(aes(x=manufacturer, y=cyl, fill=count))+
  geom_tile()+ geom_text(aes(label=count))

enter image description here