简体   繁体   中英

Draw heatmap tiles for all combination of x-y

I asked a question about the heatmap which was solved here: custom colored heatmap of categorical variables . I defined my scale_fill_manual for all combinations as suggested in the accepted answer.

Based on this question, I would like to know how to tell ggplot2 to plot a heatmap with all combination of variables and not just the ones that are available in the dataframe (given that they are already in the scale_fill_manual but are not showing in the final plot).

How can I do this?

The current plotting code:

df <- data.frame(X = LETTERS[1:3], 
                 Likelihood = c("Almost Certain","Likely","Possible"), 
                 Impact = c("Catastrophic", "Major","Moderate"), 
                 stringsAsFactors = FALSE)
df$color <- paste0(df$Likelihood,"-",df$Impact)

ggplot(df, aes(Impact, Likelihood)) + geom_tile(aes(fill = color),colour = "white") + geom_text(aes(label=X)) +
  scale_fill_manual(values = c("Almost Certain-Catastrophic" = "red","Likely-Major" = "yellow","Possible-Moderate" = "blue"))

scale_fill_manual contains all combination of Impact, Likelihood with their respective colors.

Similar to @aosmith I tried expand.grid to get a finite set of combinations but tidyr::complete() works pretty nice as well. Add the colors and letters and fill using a set color range.

df <- data.frame(Likelihood = c("Almost Certain","Likely","Possible"), 
                 Impact = c("Catastrophic", "Major","Moderate"), 
                 stringsAsFactors = FALSE)
df2 <- df %>% tidyr::complete(Likelihood,Impact) # alt expand.grid(df)

df2$X <- LETTERS[1:9] # Add letters here
df2$color <- paste0(df2$Likelihood,"-",df2$Impact) # Add colors


ggplot(df2, aes(Impact, Likelihood)) + geom_tile(aes(fill = color),colour = "white") + geom_text(aes(label=X)) +
  scale_fill_manual(values = RColorBrewer::brewer.pal(9,"Pastel1"))

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.

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