简体   繁体   中英

R: ggplot heatmap color change

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?

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

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

在此处输入图片说明

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