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.
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())
