0
df.team_data <- expand.grid(teams = c("Team A", "Team B", "Team C", "Team D")
                           ,metrics = c("Metric 1", "Metric 2", "Metric 3", "Metric 4", "Metric 5")
                           )
set.seed(41)
df.team_data$performance <- sample(c(0, 1), 20, replace = TRUE)

head(df.team_data)
ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
  geom_tile(aes(fill = performance)) 

enter image description here

I have a very simple heatmap with just two colors. How do I designate which colors are associated with the value of performance? For this, I would like performance of 1 to be dark blue, and performance of 0 to be light blue. Also, is there a way to change the legend to be binary?

Adrian
  • 9,229
  • 24
  • 74
  • 132

2 Answers2

2

The values in the "performance" column of your data set is in "numeric" format. Convert that in to a factor using factor() and your graph will have a binary legend:

df.team_data <- expand.grid(teams = c("Team A", "Team B", "Team C", "Team D")
                            ,metrics = c("Metric 1", "Metric 2", "Metric 3", "Metric 4", "Metric 5")
)
set.seed(41)
df.team_data$performance <- sample(c(0, 1), 20, replace = TRUE)

df.team_data$performance<-factor(df.team_data$performance)
head(df.team_data)
library(ggplot2)

ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
  geom_tile(aes(fill = performance))

updated

 col.plot<-c('lightblue','darkblue')
 ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
      geom_tile(aes(fill = performance))+scale_fill_manual(values=col.plot)

change the values in col.plot as per your need

Ishan Juneja
  • 401
  • 4
  • 11
2

If you use scale_fill_gradient() and set several options regarding the colours for high and low values, I think you could get what you are after. Also you can set the breaks in your performance variable with breaks ().

Using your code I obtain the following:

df.team_data <- expand.grid(teams = c("Team A", "Team B", "Team C", "Team D")
                            ,metrics = c("Metric 1", "Metric 2", "Metric 3", "Metric 4", "Metric 5")
)

df.team_data$performance <- sample(c(0, 1), 20, replace = TRUE)

head(df.team_data)
ggplot(data = df.team_data, aes(x = metrics, y = teams)) +
  geom_tile(aes(fill = performance)) + scale_fill_gradient('performance', limits=c(0, 1), breaks = c(0, 0.25, 0.5, 0.75, 1),  low = "lightblue", high = "darkblue") 

enter image description here

Edu
  • 903
  • 6
  • 17
  • I agree with the use of `scale_fill_gradient()`. Typically heatmaps have more than two values, and the response above would only work in that case. Since this is the first hit for "ggplot2 heatmap color change", I think its worth mentioning. – ssanch Aug 17 '18 at 17:07