dan
dan

Reputation: 6304

Getting geom_tile to draw square rather than rectangular cells

I'm trying to generate a heatmap plot using ggplot's geom_tile. My data have far more rows than columns.

  set.seed(1)
  df <- data.frame(val=rnorm(100),gene=rep(letters[1:20],5),cell=c(sapply(LETTERS[1:5],function(l) rep(l,20))))

Running:

library(ggplot2)
ggplot(df,aes(y=gene,x=cell,fill=val))+geom_tile(color="white")

produces: enter image description here

How do I get the heatmap cells to be of symmetric dimensions - squares instead of rectangles (height=width)? without distorting the dimensions of the figure.

Upvotes: 23

Views: 16247

Answers (2)

mpalanco
mpalanco

Reputation: 13570

An option is to add coord_equal.

The default, ratio = 1, ensures that one unit on the x-axis is the same length as one unit on the y-axis

ggplot(df, aes(y = gene, x = cell, fill = val)) +
  geom_tile(color = "white") +
  coord_equal()

enter image description here

Upvotes: 45

nathanesau
nathanesau

Reputation: 1721

Tweak the ratio as follows

set.seed(1)
df <- data.frame(val=rnorm(100),gene=rep(letters[1:20],5),
             cell=c(sapply(LETTERS[1:5],function(l) rep(l,20))))

library(ggplot2)
p <- ggplot(df,aes(y=gene,x=cell,fill=val))+geom_tile(color="white")
p <- p + coord_fixed(ratio = 0.7)
p

enter image description here

Upvotes: 5

Related Questions