Charly
Charly

Reputation: 35

How can I set individual column widths in geom_tile (in ggplot2)

I was wondering whether someone could help me with this: I want to set the widths of individual columns in a ggplot2 geom_tile heatmap to distinct values.

library(ggplot2)
library(data.table)

ggplot(data = melt(as.matrix(mtcars))) + geom_tile(aes(x=Var2, y=Var1,fill = value))

I would like the first column (mpg) to have a width of, say, 5, the second one 2, etc.

thank you

Upvotes: 2

Views: 1198

Answers (1)

Dan Adams
Dan Adams

Reputation: 5254

geom_tile() has a width argument you can use to programmatically set the width. But you have to be careful because the labels will end up in funny places if you're not explicit about where to put them. Therefore I pre-calculate the position of each label based on the specified widths. Here you also have to know the order you want these columns in so they appear correctly.

library(tidyverse)

# set widths of each column and calculate position for lables and boxes
widths <- tibble(param = fct_inorder(names(mtcars)),
                 width = c(5, 2, rep(1, 9)), 
                 x_end = cumsum(width), 
                 x_pos = x_end - width/2
                 )

# plot and specify precalculated labels
mtcars %>% 
  rownames_to_column("car") %>%
  pivot_longer(-car, "param") %>% 
  left_join(., widths) %>% 
  ggplot(aes(x_pos, car, fill = value)) +
  geom_tile(aes(width = width)) +
  scale_x_continuous(breaks = widths$x_pos, labels = widths$param)
#> Joining, by = "param"

Created on 2022-02-14 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions