so I have run into a minor issue with drawing heat maps using geom_tile() and dplyr package. 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. 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?
I have tried using the na.value argument in scale_fill_gradient, but it does not work. I assume since there are no NAs in the table. 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()
.
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.
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"))
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:
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.