1

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 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

How can text appear only once in the area? I have tried geom_text() but that makes the Cat 'GONE' appear 3 times in each of the boxes. I want GONE to apear once and this is the code I have tried so far. df %>% ggplot(aes(B, A, fill = Cat)) + geom_raster() + geom_text(aes(label = Cat)) + ylim(c(0.5, 3))
See if my edited answer helps :)
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.