scbears88
scbears88

Reputation: 67

Ggplot Heatmap - customized colors for customized count ranges

I want to make a heatmap that creates a group of clarity & color combinations as the X axis and cut as the Y axis. The heatmap would color based upon the counts of clarity+color and its intersection with the cut.

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

Upvotes: 0

Views: 868

Answers (1)

Robert
Robert

Reputation: 5152

Try this:

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

Upvotes: 1

Related Questions