如何在ggplot heatmap中更改空单元格的填充颜色

时间:2017-11-08 06:09:05

标签: r ggplot2 heatmap

我有一个数据集,其x变量有一些缺失值。例如,下面的数据框显示181930和610有一整套x变量,1-7,而1044,1114等只有一个。

{"error":{"code":"InvalidRequestContent","message":"The request content was invalid and could not be deserialized: 'Could not find member 'encryption' on object of type 'ResourceDefinition'. Path 'encryption', line 1, position 47.'."}}

我想使用ggplot生成一个热图,显示值为1的单元格。这是我的代码到目前为止,但是对于只有一个xvar的标签显示一个空白单元格,而我希望它有一个颜色(白色)匹配0值。

label   xvar value
181930  1    0
181930  2    0
181930  3    1
181930  4    0
181930  5    0
181930  6    0
181930  7    1
610  1    0
610  2    0
610  3    0
610  4    0
610  5    1
610  6    1
610  7    0
1044  1    0
1114  1    0
1156  1    1
1378  1    0
1834  1    1

不幸的是,na.value并不适合我。这是一张照片: plot

2 个答案:

答案 0 :(得分:2)

有时在 ggplot2 中执行某项操作的简单方法是在绘图之前操作数据集。在这种情况下,扩展数据集使其包含您要绘制的所有组合是一个选项。

我使用tidyr::complete以及来自包 dplyr 的分组。对于每xvar,这会为label的1到7添加一行。如果该行当前不存在,则会使用NA填充缺失值。 NA似乎足以满足您的使用案例,但您也可以使用fill参数将缺失值设置为0或其他内容。

library(dplyr)
library(tidyr)

longdf = activeDF %>%
     group_by(label) %>%
     complete(xvar = 1:7)

longdf

# A tibble: 49 x 3
# Groups:   label [7]
   label  xvar value
   <int> <int> <int>
 1   610     1     0
 2   610     2     0
 3   610     3     0
 4   610     4     0
 5   610     5     1
 6   610     6     1
 7   610     7     0
 8  1044     1     0
 9  1044     2    NA
10  1044     3    NA
# ... with 39 more rows

使用展开的数据集,您的绘图现在会扩展整个数据范围,因此平铺已完成。

ggplot(longdf, aes(xvar, factor(label)) ) +
     geom_tile(aes(fill = value), colour = 'black') + 
     scale_x_continuous(breaks = round(seq(0, 7))) +
     scale_fill_gradient(high = brewer.pal(10, 'PiYG')[8], low='white', na.value = 'white')

enter image description here

答案 1 :(得分:0)

试试这个+ theme(panel.background = element_rect(fill = 'white'))

ggplot(activeDF,aes(xvar,factor(label)))+
geom_tile(aes(fill=value),colour='white')+ 
scale_x_continuous(breaks=round(seq(0,7)))+
scale_fill_gradient(high=brewer.pal(10,'PiYG')[8],low='white',na.value = 'white') +
theme(panel.background = element_rect(fill = 'white'))
相关问题