Ggplot热图 - 为自定义计数范围定制颜色

时间:2016-08-01 17:56:20

标签: r plot ggplot2 heatmap

我想创建一个热图,创建一组清晰度&颜色组合为X轴,切割为Y轴。热图将根据清晰度+颜色及其与切口的交点进行着色。

library(ggplot2)
library(dplyr)

 ## rename diamonds df
 #  1.   Generate a count for the frequency of cut+clarity 
 #  2.   Make a heatmap of this using the following bins
 #  3.    Red <= 100 Frequency
          Yellow  = between (100 and 500)
          Green   > 500
# place counts inside the cell:

df = diamonds %>% 
select( cut, clarity) %>%
 group_by(cut,clarity)%>% 
mutate(count  = n())

myplot = ggplot(df, aes(x = clarity, y=cut)) + 
geom_bin2d( bins = c(100,500,50000), col='orange')  # 
geom_text( aes(label = count),col='red')

myplot

1 个答案:

答案 0 :(得分:1)

试试这个:

df$col <- cut(df$count,breaks = c(-Inf,100,500,Inf),right = TRUE)
df$color<-df$col
levels(df$color) <- c("<=100","100<#<=500",">500")

ggplot(data =  df, aes(x = clarity, y = cut)) + 
  geom_tile(aes(fill = df$color), colour = "white") +
  scale_fill_brewer("Count",palette = "Set1")+
geom_text(aes(label = count),col='yellow',cex=3)

![enter image description here