R: ggplot heatmap color change

亡梦爱人 提交于 2019-12-25 15:15:13

问题


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



来源:https://stackoverflow.com/questions/43133521/r-ggplot-heatmap-color-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!