Home > Enterprise >  ggplot: Can I make a heatmap where intensity is indicated by area covered rather than color?
ggplot: Can I make a heatmap where intensity is indicated by area covered rather than color?

Time:07-15

I have data from a 2d grid, where each entry has an intensity value. I'd like to plot these data in something like a heatmap, but where intensity is indicated as the proportion of area covered within each cell, rather than the hue. Something along the lines of the attached image. How would you approach doing that with ggplot?

Many thanks!! -Matan

An odd mixture of a histogram and a heatmap

CodePudding user response:

Here is an example of converting a matrix (in this case of squared correlation values) to an area-based heatmap.

library(ggplot2)

cor <- cor(mtcars)^2

df <- reshape2::melt(cor)
# Make sure the thing that you're mapping to area is between 0 and 1
df$value <- scales::rescale(df$value, to = c(0, 1))

ggplot(df, aes(Var1, Var2))  
  # Cell outlines
  geom_tile(colour = "black", fill = NA)  
  # Area fills, convert factors to numeric
  geom_rect(
    aes(xmin = as.numeric(Var1) - 0.5, 
        xmax = as.numeric(Var1)   0.5,
        ymin = as.numeric(Var2) - 0.5,
        ymax = as.numeric(Var2) - 0.5   value),
    
  )

Created on 2022-07-15 by the reprex package (v2.0.1)

A slightly more robust version that still allows you to rearrange the x/y-axis afterwards:

  geom_rect(
    aes(xmin = stage(Var1, xmin - 0.5),
        xmax = stage(Var1, xmax   0.5),
        ymin = stage(Var2, ymin - 0.5),
        ymax = stage(value, ymin - 0.5   ymax))
  )
  • Related