2

This code for a heatmap, is from a previous answer here. I've changed it so it displays four decimal places:

Previous Answer

library(tidyverse)
## make data
dat <- matrix(rnorm(100, 3, 1), ncol=10)

## reshape data (tidy/tall form)
dat2 <- dat %>%
  tbl_df() %>%
  rownames_to_column('Var1') %>%
  gather(Var2, value, -Var1) %>%
  mutate(
    Var1 = factor(Var1, levels=1:10),
    Var2 = factor(gsub("V", "", Var2), levels=1:10)
  )

## plot data
ggplot(dat2, aes(Var1, Var2)) +
  geom_tile(aes(fill = value)) + 
  geom_text(aes(label = round(value, 4))) +
  scale_fill_gradient(low = "white", high = "red")

With four decimal places my output looks like this:

enter image description here

How can I:

  1. Make the cells large enough to contain all of the digits
  2. Make the cells square, i.e. not rectangular (so that they look like the output in the original answer)
  3. Force the display of significant digits so that say 0.9 displays as 0.9000

Thank you.

Jeremy K.
  • 1,710
  • 14
  • 35
  • Add `size = 2` (or some other small number, depending on your plot size) to `geom_text()` to fit the labels within each cell. Add `coord_fixed()` to make the cells square. I'm not sure if I understand your 3rd question... – Z.Lin Oct 18 '17 at 02:15
  • @Z.Lin Thank you so much, it works really well now. With 3. I was meant to be asking "Force the display of significant digits so that say 0.9 displays as 0.9000" Thanks again. – Jeremy K. Oct 18 '17 at 02:32
  • @Z.Lin Also, I wonder how I can make the cells larger? I tried `geom_tile(aes(fill = coeffvalue), size = 4)` but the `size=` didn't seem to increase the cell size. Thank you. – Jeremy K. Oct 18 '17 at 03:03
  • The accepted answer [here](https://stackoverflow.com/a/38370083/8449629) should address the display of significant digits. The overall height & width of your heatmap depends on your plot area, so the individual cells aren't going to get larger unless you increase the size of your plot. – Z.Lin Oct 18 '17 at 04:03
  • @Z.Lin Thank you so much! Everything works great now. Really appreciate your help. – Jeremy K. Oct 18 '17 at 05:21

1 Answers1

2

Thank you to Z.Lin for this which works perfectly.

library(tidyverse)

## make data
dat <- matrix(rnorm(100, 3, 1), ncol=10)

## reshape data (tidy/tall form)
dat2 <- dat %>%
  tbl_df() %>%
  rownames_to_column('Var1') %>%
  gather(Var2, value, -Var1) %>%
  mutate(
    Var1 = factor(Var1, levels=1:10),
    Var2 = factor(gsub("V", "", Var2), levels=1:10)
  )

## plot data
ggplot(dat2, aes(Var1, Var2)) +
  geom_tile(aes(fill = value)) + 
  geom_text(aes(label = round(value, 4)), size = 2) +
  scale_fill_gradient(low = "white", high = "red") + coord_fixed()

Result

Jeremy K.
  • 1,710
  • 14
  • 35