Holger Brandl
Holger Brandl

Reputation: 11192

How to overlay geom_tile heatmap with second indicator geom_tile layer?

I'm trying to highlight a single tile in a heatmap with

ggplot(faithfuld, aes(waiting, eruptions)) +
    geom_raster(aes(fill = density)) +
    geom_tile(data = faithfuld[50, ],  fill = "red")

However, the result is not highlighting the (here randomly selected) tile, but rather adds some more arbitray tile.

enter image description here

Why is that, and how would I add my second geom_tile layer with correct tile dimensions?

Upvotes: 2

Views: 692

Answers (1)

Arienrhod
Arienrhod

Reputation: 2581

The geom_tile in your image highlights the exact tile you want (it takes the given data points and sets them as the centre of the tile), but it's hard to see this because the tile it creates is very long. If you play with width and height settings, you can get something more reasonable.

ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density)) +
  geom_tile(data = faithfuld[50, ],  width = 1, height = 0.1, fill = "red")

example

EDIT:

How to get the exact height and width of geom_raster and use it with geom_tile (the default values are 1 for both):

p <- ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density))

tmp <- ggplot_build(p)$data[[1]][2,]  # get the first data point from geom_raster
width <- tmp$xmax - tmp$xmin  # calculate the width of the rectangle
height <- tmp$ymax - tmp$ymin  # calculate the height of the rectangle
p <- p +
  geom_tile(data = faithfuld[50, ],  width = width, height = height, fill = "red")

example 2

There are also other solutions, like this one where you make the variables categorical.

Upvotes: 1

Related Questions