简体   繁体   English

R dplyr热图处理缺失值

[英]R dplyr heatmap dealing with missing values

so I have run into a minor issue with drawing heat maps using geom_tile() and dplyr package. 所以我在使用geom_tile()和dplyr包绘制热图时遇到了一个小问题。 I assume that it is a simple solution, but I have not been able to find the answer anywhere yet. 我认为这是一个简单的解决方案,但是我还无法在任何地方找到答案。 Apologies if there is one out there and I just missed it. 抱歉,如果没有,我只是错过了。

So the following code is for a trivial example: 因此,以下代码是一个简单的示例:

Trivial <- tibble(
  Name1 = c("a","b","c"),
  Name2 = c("x","y","z"),
  Value = c(1,2,3)
)
Trivial %>%
  ggplot(aes(Name1, Name2)) +
    geom_tile(aes(fill = Value)) +
    scale_fill_gradient(low = "white", high = "green")

The heat map produced by this shows grey/blank space where there is no information for those combinations of Name1 and Name2. 由此产生的热图显示灰色/空白空间,其中没有有关Name1和Name2的组合的信息。 Is there a way of instead of showing blank space I could fill it with white (or any other colour)? 有没有一种方法可以代替显示空白,而是可以用白色(或任何其他颜色)填充它? Alternatively, could I put a "NA" on the plot to show that those blank spaces are indeed meant to be blank? 或者,我可以在图上放一个“ NA”以表明那些空白确实意味着要空白吗?

I have tried using the na.value argument in scale_fill_gradient, but it does not work. 我已经尝试在scale_fill_gradient中使用na.value参数,但是它不起作用。 I assume since there are no NAs in the table. 我假设因为表中没有NA。 However, I think that could be a way forward. 但是,我认为这可能是前进的道路。 I will keep experimenting, but any help would be greatly appreciated! 我会继续尝试,但任何帮助将不胜感激!

Thank you! 谢谢!

Or you can just add them_classic() . 或者,您可以只添加them_classic()

Trivial %>%
    ggplot(aes(Name1, Name2)) +
    geom_tile(aes(fill = Value)) +
    scale_fill_gradient(low = "gray", high = "green") + 
    theme_classic()

图片

I just used low= "gray" because background is white. 我只用了low= "gray"因为背景是白色的。

You can change also the background : 您还可以更改背景:

Trivial %>%
    ggplot(aes(Name1, Name2)) +
    geom_tile(aes(fill = Value)) +
    scale_fill_gradient() + 
    theme_classic() +
    theme(panel.background = element_rect(fill = "white", colour = "white"))

图像2

You can use expand() from tidyr to get all combinations of Name1 and Name2 and then fill all NA with 0 and then plot the heatmap: 您可以使用expand()tidyr得到的所有组合Name1Name2 ,然后填充所有NA0 ,然后绘制热图:

library(tidyr)      
Trivial %>% expand(Name1, Name2) %>% 
  left_join(Trivial, by = c("Name1", "Name2")) %>%
  mutate( Value = ifelse(is.na(Value), 0, Value)) %>%
  ggplot(aes(Name1, Name2)) +
  geom_tile(aes(fill = Value)) +
  scale_fill_gradient(low = "white", high = "green")

The result looks like this: 结果看起来像这样:

产量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM