df <-expand.grid(x =1:5, y =1:5); df$z <-runif(25)ggplot(df, aes(x, y, fill = z)) +geom_tile(color ="white", linewidth =1)
Exercise 12: Tile from a count table
Difficulty: Advanced.
Show solution
RInteractive R
diamonds |>count(cut, color) |>ggplot(aes(cut, color, fill = n)) +geom_tile() +scale_fill_viridis_c()
Exercise 13: Mask diagonal
Difficulty: Advanced.
Show solution
RInteractive R
m <-cor(mtcars[, 1:5])m[lower.tri(m, diag =FALSE)] <-NAdf <-as.data.frame(m) |> tibble::rownames_to_column("v1") |>pivot_longer(-v1, names_to ="v2", values_to ="cor") |>na.omit()ggplot(df, aes(v1, v2, fill = cor)) +geom_tile() +scale_fill_gradient2(low ="blue", high ="red")
Exercise 14: Limit color range
Difficulty: Advanced.
Show solution
RInteractive R
df <-expand.grid(x =1:5, y =1:5); df$z <-runif(25)ggplot(df, aes(x, y, fill = z)) +geom_tile() +scale_fill_gradient(low ="white", high ="red", limits =c(0, 1))
Exercise 15: Annotate cells with formatted numbers
Difficulty: Advanced.
Show solution
RInteractive R
m <-cor(mtcars[, 1:5])df <-as.data.frame(m) |> tibble::rownames_to_column("v1") |>pivot_longer(-v1, names_to ="v2", values_to ="cor")ggplot(df, aes(v1, v2, fill = cor)) +geom_tile() +geom_text(aes(label =sprintf("%.2f", cor)), color ="black", size =3) +scale_fill_gradient2(low ="blue", high ="red")
Exercise 16: Faceted heatmap
Difficulty: Advanced.
Show solution
RInteractive R
df <-expand.grid(x =1:3, y =1:3, group =c("A","B"))df$z <-runif(nrow(df))ggplot(df, aes(x, y, fill = z)) +geom_tile() +facet_wrap(~ group)