ifreak
ifreak

Reputation: 1756

custom colored heatmap of categorical variables

I have searched a lot for a solution to this problem, and only found this similar question where the solution for a similar problem is described but seems to be too complicated.

ggplot2 heatmaps: using different gradients for categories

I would like to know if there is another EASIER solution for a similar problem.

I have a simple dataframe:

,X,Likelihood,Impact
1,A,Almost Certain,Catastrophic
2,B,Likely,Major
3,C,Possible,Moderate
4,D,Likely,Minor
5,E,Rare,Incidental
6,F,Unlikely,Incidental
7,G,Unlikely,Incidental

From which I want to build a heatmap. This is straightforward using:

ggplot(df, aes(Impact, Likelihood)) + 
  geom_tile(aes(fill = X), colour = "white") + 
  geom_text(aes(label = X))

However, the color are distributed randomly, what I want to have is a custom color for each pair of (Impact, Likelihood). E.g., the tile for the pair (Almost Certain, Catastrophic) should be colored in 'red'.

How can I achieve this?

Upvotes: 2

Views: 2292

Answers (2)

shaojl7
shaojl7

Reputation: 575

You can create another column as the combination of likelihood and impact, and use named vector as the colors in scale_fill_manual For example,

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"))

Upvotes: 3

tonytonov
tonytonov

Reputation: 25608

Just add the scale like so:

+ scale_fill_manual(
    values = c("red", "green", "#cbf442", "magenta", "white", "#523a56", "yellow"))

enter image description here

Upvotes: 0

Related Questions