Home > Mobile >  How to control the height of geom_tile()
How to control the height of geom_tile()

Time:02-13

With this dataframe:

df <- structure(list(region = c("AA", "BB", "CC", "DD"), event1 = c("XXX", 
"XXX", "XXX", "XXX"), value = c(3, 1, 2, 2)), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))

  region event1 value
  <chr>  <chr>  <dbl>
1 AA     XXX        3
2 BB     XXX        1
3 CC     XXX        2
4 DD     XXX        2

Using this code:

ggplot(df, aes(x = region, y = event1,  fill = value))  
  geom_tile(height=1, colour="white", size=0.5)   
  geom_text(aes(label = value), color = "grey20", size = 5)  
  scale_fill_gradientn(colours=  c("green","white","red"),, na.value = "transparent",
                       breaks=c(1,2,3,4),
                       labels = c("1 - A", "2 - B", "3 - C", "4 - D"),
                       limits=c(0.5,4.5))

I get this plot:

enter image description here

My desired output: enter image description here

How can I modify the code to control the height of the tiles?

CodePudding user response:

One option to achieve your desired result would be to increase the expansion of the scale:

library(ggplot2)

ggplot(df, aes(x = region, y = event1,  fill = value))  
  geom_tile(height=1, colour="white", size=0.5)   
  geom_text(aes(label = value), color = "grey20", size = 5)  
  scale_y_discrete(expand = expansion(add = c(.6, 3)))  
  scale_fill_gradientn(colours=  c("green","white","red"),, na.value = "transparent",
                       breaks=c(1,2,3,4),
                       labels = c("1 - A", "2 - B", "3 - C", "4 - D"),
                       limits=c(0.5,4.5))

  • Related