R: ggplot heatmap color change

2019-08-20 11:52发布

问题:

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

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?

回答1:

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



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