0

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
scbears88
  • 67
  • 1
  • 6
  • Use `cut()` to "discretize" your continuous variable and then use a custom scale to specify your colors like this this question: http://stackoverflow.com/questions/26103140/how-can-i-create-a-custom-colour-scale-using-ggplot2-and-geom-tile/26103786#26103786 or this one: http://stackoverflow.com/questions/10981324/ggplot2-heatmap-with-colors-for-ranged-values/10982332#10982332. Don't bother with geom_bin2d, that's really helpful for binning x and y values but you already have discrete values there. – MrFlick Aug 01 '16 at 18:16

1 Answers1

1

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

Robert
  • 5,038
  • 1
  • 25
  • 43