0

I'm trying to combine a geom_tile and geom_bar plot while splitting the legends.

My sample data looks like this:

for_bar_plot  <- read.table(text="
sample  category    count   Date
Sample1 cat1    65  221116
Sample1 cat2    8978    221116
Sample2 cat1    3961    221116
Sample2 cat2    341 221116
Sample3 cat1    47  221116
Sample3 cat2    9860    221116
Sample4 cat1    54  230331
Sample4 cat2    7625    230331
Sample5 cat1    70  230331
Sample5 cat2    9807    230331", header=TRUE)

This code does what I want; it makes a stacked barplot of the counts of the two categories for each sample, and underneath, there is a solid color indicating what date each sample has:

ggplot(for_bar_plot) +
  geom_bar(aes(x = sample, fill = category, y = count), position = 'stack', stat = 'identity') +
  geom_tile(aes(x = sample, y = -3000, fill = factor(Date), height = 3000), show.legend = TRUE)

Except it makes one legend with Date and category together. How can I make two separate legends? Is geom_tile the wrong choice here?

swbarnes2
  • 101
  • 1
  • 3
    Welcome to SO! In `ggplot2` you can only have one legend per scale or aesthetic. To overcome this limitation have a look at the `ggnewscale` package. For more help please provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data best shared via `dput()`. – stefan Jun 07 '23 at 21:20
  • Thanks for fixing the format, that sample data and that code do work together. – swbarnes2 Jun 07 '23 at 22:05
  • Try `ggplot(...) + geom_bar(...) + ggnewscale::new_scale_fill() + geom_tile(...)` to add a second fill legend. – stefan Jun 07 '23 at 22:12
  • new_scale_fill between them works, and lets me use two scale_fills to adjust the colors. Make your comment an answer, and I'll check it. – swbarnes2 Jun 07 '23 at 22:58

0 Answers0