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

Ggplot Heatmap - customized colors for customized count ranges

我想制作一个热图,以创建一组清晰度和颜色组合作为 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

试试这个:

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)