I am trying to create a plot like the following:

That is, a plot which has darker color based on the value (with white representing 0) in ggplot.
I have some dataframe
library(tidyverse)
library(ggplot2)
macs <- c(1,2,3,4,5,6)
KP <- c(4,5,0,7,8,2)
PF <- c(4,6,8,0,3,1)
df <- data.frame(macs,KP,PF)
rownames(df) <- c("PelTrawl","DemTrawl","KelpHarv","DemSeine","Rifles","Nets")
That I would like to create the plot out of. For example, I would like tiles with 0 in to be white, whilst tiles with larger numbers to have higher opacity (like is seen in the plot provided).
I tried using the heatmap or tile ggplots but I couldn’t quite figure out what to put in the aes(). ie
ggplot() +
geom_tile(df,aes(x = ?,y = ?, color = ?))
Thank you
>Solution :
You need to reshape your data into an appropriate format for plotting. Firstly, convert the rownames to a column using rownames_to_column. Then, you need to pivot to long format. This means that instead of having three variables, each containing numbers, you have two variables: one labelling the measurement as coming from either ‘macs’, ‘KP’, or ‘PF’, and another containing the value of the measurement. You can achieve this with pivot_longer. This allows you to have the variable name as a categorical x axis, and the value as the fill color.
For completeness, you can rearrange the column and row names to be in the same order in which they appear in your data by converting them to factors.
The rest is simply theming.
rownames_to_column() %>%
mutate(rowname = factor(rowname, rev(rowname))) %>%
pivot_longer(-rowname, names_to = 'colname') %>%
mutate(colname = factor(colname, c('macs', 'KP', 'PF'))) %>%
ggplot(aes(colname, rowname, fill = value)) +
geom_tile(color = 'black', linewidth = 0.5) +
scale_fill_gradient(low = 'white', high = '#a020f0', guide = 'none') +
labs(x = NULL, y = NULL) +
coord_equal(expand = FALSE) +
theme_bw(base_size = 16) +
theme(axis.text = element_text(color = 'black'),
axis.ticks.length.y = unit(5, 'mm'),
axis.ticks.length.x = unit(0, 'mm'),
axis.text.x.bottom = element_text(angle = 45, hjust = 1))
