Search code examples
rgeom-tile

Adding zero values where none exists for geom_tile


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))

Solution

  • 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