R:使用ggplot2将data.frame转换为颜色矩阵?

时间:2018-05-01 23:43:06

标签: r matrix ggplot2 colors

有没有人知道如何使用ggplot2将R中的数据帧与连续值转换为漂亮的数字。这与this post的回答相似,但与ggplot2相似。

这可能吗?

R和ggplot2的新手,所以提前感谢任何建议。

1 个答案:

答案 0 :(得分:1)

以下是使用mtcars数据的示例(缩放以提供可比较的值,因此数字并不重要)。

关键是使用gather整理数据,geom_tile按值填充,geom_text表示标签。其他一切只是对特定数据框的操纵。

你也可以使用其中一个scale_fill_gradient geoms。

library(tidyverse)
library(viridis)

mtcars %>% 
  scale() %>% 
  as.data.frame() %>% 
  rownames_to_column(var = "make") %>% 
  gather(var, val, -make) %>% 
  ggplot(aes(var, make)) + 
    geom_tile(aes(fill = val)) + 
    geom_text(aes(label = round(val, 2)), 
              size = 3) + 
    coord_fixed() + 
    scale_fill_viridis() + 
    guides(fill = FALSE)

enter image description here

或使用:

+ scale_fill_gradient2(midpoint = 1.5)

enter image description here