Mostrando entradas con la etiqueta heatmap. Mostrar todas las entradas
Mostrando entradas con la etiqueta heatmap. Mostrar todas las entradas

2019-06-18

How to draw square cells with geom_tile in ggplot2

Problem

In the following plot created using geom_tile we have rectangular cells. How can we draw squared cells instead?

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)
ggplot(df, aes(y = gene, x = cell, fill = val)) +
  geom_tile(color = "white")

Soluction

We add coord_fixed() or 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_fixed() # or coord_equal()

References

Related posts

2016-10-07

Obtener celdas cuadradas en lugar de rectangulares con geom_tile en ggplot2

Problema

Tenemos el siguiente gráfico cuyas celdas, creadas con geom_tile, son rectángulos. ¿Cómo conseguimos que sean cuadrados con ggplot2?

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)
ggplot(df, aes(y = gene, x = cell, fill = val)) +
  geom_tile(color = "white")

Solución

Añadimos coord_equal( ). Por defecto, el argumento es ratio = 1, y asegura que una unidad en el eje x tenga la misma longitud que una unidad en el eje y.

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

Referencias

Entradas relacionadas

Nube de datos