带有值的热图(ggplot2) - 如何使单元格正方形并自动调整大小?

时间:2017-10-18 02:06:34

标签: r ggplot2

此热图的代码来自此前的答案。我已将其更改为显示四位小数:

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

有四个小数位,我的输出如下:

enter image description here

我怎么能:

  1. 使单元格足够大以包含所有数字
  2. 使单元格成正方形,即不是矩形(使它们看起来像原始答案中的输出)
  3. 强制显示有效数字,以便说0.9显示为0.9000
  4. 谢谢。

1 个答案:

答案 0 :(得分:2)

感谢Z.Lin的完美工作。

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