How to create this chart in R or ggplot

Viewed 59

Below is the code to create the data frame.

df <- data.frame (ID  = c('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9','C10', 'C11', 'C12','C13', 'C14'),
                  A = c(1, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 2), 
                  B = c(3, 3, 1, 1, 1, 1, 1, 2, 3, 3, 2, 2, 2, 2)
                  )

Code to create the Category column:

df$Cat <- ifelse(df$A == 2 & df$B == 2, 'MID',
                 ifelse(df$A == 2 & df$B == 1, 'GONE', 
                        ifelse(df$A == 1 & df$B == 1, 'GONE', 
                               ifelse(df$A == 1 & df$B == 2, 'GONE', 
                                      ifelse(df$A == 2 |df$A == 1 & df$B == 3, 'UP',
                               
                               'NO')))))

The chart I need to create: enter image description here

How can I create the chart I want from the data above? I have tried using Treemaps for this but I don't think that will work because it only allows comparing quantities by size in a fixed space. So what can be used? Any help will be greatly appreciate

2 Answers

What you need is geom_raster.

To label the tiles as in your question, I would create an extra dataframe called df_annotate with all the aes specifies in that dataframe. In this case, you can control where the label appears on the graph (just set different A and B values as you like).

Here I set the values of A and B so that the labels appears at the position similar to your drawing. Remember to use data = df_annotate in the geom_text().

Prepare df_annotate for geom_text

library(tidyverse)

df_annotate <- df %>% group_by(Cat) %>% 
  summarize(sum_Cat = n()) %>% 
  mutate(sum_Cat_number = paste(sum_Cat, Cat), 
         A = c(1, 2, 1.5), 
         B = c(2, 2, 3))

ggplot

df %>% 
  ggplot(aes(B, A, fill = Cat)) + 
  geom_raster() +
  ylim(c(0.5, 3)) +
  geom_text(data = df_annotate, aes(B, A, label = sum_Cat_number), inherit.aes = F)

geom_raster_df_annotate

Try a heatmap with ggplot2 using geom_tile()

ggplot(df, aes(A, B, fill= Cat)) + 
  geom_tile() +
  scale_fill_manual(values = c("blue", "green", "red")) +
  geom_text(aes(label = Cat), size=5)

enter image description here

Related