CheckThis
CheckThis

Reputation: 49

Why does this code not create a heat map in R using ggplot?

Suppose we have a data frame df that looks like:

                team_1   team_2   team_3
very_effective   3        5        8
effective        5        6        9  
ineffective      6        8        20

I want to create a heatmap that has different colour squares which are darker if the value is higher. I tried the following code but I get the error object 'X1' is not found. Does anyone know how to fix? Thanks!

library(ggplot2)
ggp <- ggplot(df, aes(X1, X2)) +                           # Create heatmap with ggplot2
  geom_tile()
ggp 

Upvotes: 0

Views: 140

Answers (1)

Caspar V.
Caspar V.

Reputation: 1812

aes() expects vectors for x- and y-values; not a crosstable, and also not undefined variables:

Usage
aes(x, y, ...)

source: https://ggplot2.tidyverse.org/reference/aes.html

As a general rule, ggplot() expects all the data in long format.

Solution

Given the following data:

df <- structure(list(team_1 = c(3L, 5L, 6L), team_2 = c(5L, 6L, 8L), 
    team_3 = c(8L, 9L, 2L)), class = "data.frame", row.names = c("very_effective", 
"effective", "ineffective"))

We first add the row names as a column, as a factor to preserve their row order. Then we melt the data from a crosstable into long format:

df_plot <- df

df_plot$effect <- factor(rownames(df_plot), levels = rownames(df_plot))

df_plot <- reshape2::melt(df_plot)

Resulting data frame:

> df_plot
          effect variable value
1 very_effective   team_1     3
2      effective   team_1     5
3    ineffective   team_1     6
4 very_effective   team_2     5
5      effective   team_2     6
6    ineffective   team_2     8
7 very_effective   team_3     8
8      effective   team_3     9
9    ineffective   team_3     2

ggplot is happy to accept this data format.

On the y-axis, it will put the 'lowest' value of effect (the first value in the factor: 'very effective') on the bottom; with scale_y_discrete(limits=rev) we reverse the order.

library(ggplot2)
ggplot(df_plot, aes(x=variable, y=effect, fill=value)) +
  geom_tile() +
  scale_y_discrete(limits=rev)

enter image description here

Upvotes: 2

Related Questions