Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading