0

I would like to have a separate scale bar for each variable.

I have measurements taken throughout the water column for which the means have been calculated into 50cm bins. I would like to use geom_tile to show the variation of each variable in each bin throughout the water column, so the plot has the variable (categorical) on the x-axis, the depth on the y-axis and a different colour scale for each variable representing the value. I am able to do this for one variable using

ggplot(data, aes(x=var, y=depth, fill=value, color=value)) + 
        geom_tile(size=0.6)+ theme_classic()+scale_y_continuous(limits = c(0,11), expand = c(0, 0))

enter image description here

But if I put all variables onto one plot, the legend is scaled to the min and max of all values so the variation between bins is lost.

To provide a reproducible example, I have used the mtcars, and I have included alpha = which, of course, doesn't help much because the scale of each variable is so different

data("mtcars")
# STACKS DATA 
library(reshape2)
dat2b <- melt(mtcars, id.vars=1:2)
dat2b
ggplot(dat2b) + 
  geom_tile(aes(x=variable , y=cyl, fill=variable, alpha = value))

Which produces

enter image description here

Is there a way I can add a scale bar for each variable on the plot?

This question is similar to others (e.g. here and here), but they do not use a categorical variable on the x-axis, so I have not been able to modify them to produce the desired plot.

Here is a mock-up of the plot I have in mind using just four of the variables, except I would have all legends horizontal at the bottom of the plot using theme(legend.position="bottom")

enter image description here

Jo Harris
  • 98
  • 9

1 Answers1

0

Hope this helps: The function myfun was originally posted by Duck here: R ggplot heatmap with multiple rows having separate legends on the same graph

library(purrr)
library(ggplot2)
library(patchwork)
data("mtcars")
# STACKS DATA 
library(reshape2)
dat2b <- melt(mtcars, id.vars=1:2)
dat2b

#Split into list
List <- split(dat2b,dat2b$variable)
#Function for plots
myfun <- function(x)
{
  G <- ggplot(x, aes(x=variable, y=cyl, fill = value)) + 
    geom_tile() + 
  theme(legend.direction = "vertical", legend.position="bottom")
  return(G)
}
#Apply
List2 <- lapply(List,myfun)
#Plot
reduce(List2, `+`)+plot_annotation(title = 'My plot')

patchwork::wrap_plots(List2)

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66