Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add border around specific tiles in geom_tile()

Tags:

r

ggplot2

I have the following heatmap generated in R using geom_tile in the ggplot2 package.

# Dummy data
x <- LETTERS[1:5]
y <- paste0("var", seq(1,5))
data <- expand.grid(X=x, Y=y)
data$Z <- runif(25, 0, 5)


# Heatmap 
ggplot(data, aes(X, Y, fill= Z)) + 
  geom_tile() +
  scale_fill_gradient(low = "green", high = "red") 
  

enter image description here

Is there any way to draw a border around specific tiles only? For example, I would like to have a border around the cell in the top left hand corner (A:var5) and the cell in the centre (C:var3).

like image 557
Tanga94 Avatar asked Oct 29 '25 17:10

Tanga94


2 Answers

You could do:

ggplot(data, aes(X, Y, fill= Z)) + 
  geom_tile() + 
  geom_tile(data = data[c(13, 21),], fill = NA, color = "black", size = 2) +
  scale_fill_gradient(low = "green", high = "red") 

enter image description here

like image 76
Allan Cameron Avatar answered Nov 01 '25 07:11

Allan Cameron


Here are two methods, depending on your needs:

  1. Subset the data you want to highlight and call again to geom_tile() for that subset, with different aesthetics:
p <- ggplot(data, aes(X, Y, fill= Z)) + 
  geom_tile() +
  scale_fill_gradient(low = "green", high = "red")

d <- data.frame(X=c("A","C"), Y=c("var5", "var3"))
dat <- merge(data, d)

p + geom_tile(data=dat, aes(X,Y), fill="transparent", colour="black", size=1)
  1. Alternatively, you could just annotate the original with the coordinates for rectangles you'd like to highlight:
p + annotate("rect", xmin=c(0.5, 2.5), xmax=c(1.5, 3.5), ymin=c(4.5,2.5), ymax=c(5.5,3.5), colour="black", fill="transparent", size=1)

Results are equivalent: enter image description here

like image 35
phalteman Avatar answered Nov 01 '25 06:11

phalteman