Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

geom_tile fill tile based on logical values (0 and 1) with different fill colors by group

I have a dataframe like this:

df <- data.frame("Name" = rep(c("Aa", "Ab", "Ac", "Ba", "Ca", "Cb"), 3),
             "Level" = c(rep("High",6), rep("Medium",6), rep("Low",6)),
             "plot.fill" = c(0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1),
             "Group" = rep(c("A", "A", "A", "B", "C", "C"), 3))

I’m trying to plot this data using geom_tile. I figured out how to make the tile filled or not using the plot.fill parameter:

ggplot(df, aes(x=Name, y=Level, fill = plot.fill == 1)) +
  geom_tile() + scale_fill_manual(values = c('FALSE'="white", 'TRUE'="blue"))

But I also want to fill the tile with different colors based on Group.
I tried this but now it fills all tiles regardless of plot.fill.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ggplot(df, aes(x=Name, y=Level, fill = Group)) +
  geom_tile() + scale_fill_manual(values = c("blue","red","yellow"))  

I also tried adding aes(fill=Group) in the geom_tile arguemnt, but it gives me an error (mapping must be created by aes()). How should I combine what each code is doing to fill the tiles in different colors by Group only if the plot.fill values equal 1?

>Solution :

You could use the alpha scale, identity-mapped to plot.fill, to indicate presence / absence. This allows you to use the fill aesthetic to indicate Group:

ggplot(df, aes(Name, Level, fill = Group, alpha = plot.fill)) +
  geom_tile(color = "black") +
  scale_alpha_identity() +
  scale_fill_brewer(palette = "Set1") +
  coord_equal() +
  theme_minimal(base_size = 16) +
  theme(panel.grid = element_blank())

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading