8

I have the following code in R using the ggplot2 package to create a stacked bar plot.

ggplot(example_data, aes(x = ID, y = amount, fill = Taxa)) +
 geom_bar(stat="identity", position = "fill") +
 facet_grid(.~City+Car+Color , scales = "free_x", space = "free_x") +
 labs(y = "Relative Adbundance")+
 theme(axis.title.x = element_blank(),
       axis.ticks = element_blank(),
       axis.text.x = element_blank(),
       legend.position  = "none")

Stacked barplot

Is there a way to simply combine parts of different facets? The picture below explains what I mean. I want one gray bar saying "Milan" for all 5 facets that currently say Milan. I do not want to repeat the word "Milan" five times. Same for all the other circled groups. Is this possible in ggplot2? If not, does anyone know a work around?

Circled stacked barplot

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
nicole
  • 153
  • 1
  • 6
  • 1
    please include some sample data. Otherwise I can't help. but you can try `facet_grid(City~Car+Color` – Roman Apr 11 '18 at 13:57
  • 2
    Have a look at this answer (https://stackoverflow.com/a/44628573/3926543). A possible solution is to draw the first row and and second row seperately and combined it with the main plot with cowplot. – mt1022 Apr 11 '18 at 14:06
  • 1
    Don't think ggplot supports this. Hadley is very particular about letting people modify graphs. See [this answer](https://stackoverflow.com/questions/13651627/nested-facet-plot-with-ggplot2). – Anonymous coward Apr 11 '18 at 15:08
  • 3
    Something like [this](https://stackoverflow.com/questions/40732543/seeking-workaround-for-gtable-add-grob-code-broken-by-ggplot-2-2-0) or [this](https://stackoverflow.com/questions/39801041/ggplot2-have-common-facet-bar-in-outer-facet-panel-in-3-way-plot)? – Sandy Muspratt Apr 11 '18 at 18:41
  • 1
    @SandyMuspratt your suggestion in the first link worked great! Thanks! – nicole Apr 12 '18 at 19:50
  • @SandyMuspratt I'm having an issue with the facet_grid scales and space. I don't see how to add a picture here to show you the problem, but I will try to describe. Using code you have in the links above for my barplots I either have bars of the same width and the facets are jumbled a bit, or facets of the same size with bars of all different widths. Is there a way to have a uniform bar width, and the facets adjust to fit them properly? – nicole May 22 '18 at 13:36
  • @nicole, I think I see the problem. Give me a couple of days. – Sandy Muspratt May 23 '18 at 05:52
  • 1
    @nicole, the problem was that I assumed that the panels have the same with. Have a look at the non-accepted answer [here](https://stackoverflow.com/questions/40732543/seeking-workaround-for-gtable-add-grob-code-broken-by-ggplot-2-2-0/40986592#40986592). Should work with panels of different widths. – Sandy Muspratt May 28 '18 at 23:30
  • 1
    Worked perfectly, thanks! – nicole May 29 '18 at 15:17

0 Answers0