0

I have written the code to make bar charts for the counts of species in four habitat types. I have 8 species in total but not all species are present in each habitat. I want a multi-paneled graph of the four habitat types with a common legend for the species. Currently, each of bar charts has it's own legend with different colours corresponding to different species.

[Graph of RV][1]
[Graph of CG][2]
[Graph of U][3]
[Graph of SRG][4]

Below is the code used

ggplot(SRG, aes(x = Species)) +
geom_bar(aes(color = Species),
stat = "count", position = position_dodge(0.8),
width = 0.9)+
labs(y= "Count", x= "Species")

ggplot(U, aes(x = Species)) +
geom_bar(aes(color = Species, , fill = Species),
stat = "count", position = position_dodge(0.8),
width = 0.9)+
labs(y= "Count", x= "Species")

ggplot(CG, aes(x = Species)) +
geom_bar(aes(color = Species, fill = Species),
stat = "count", position = position_dodge(0.8),
width = 0.9)+
labs(y= "Count", x= "Species")

ggplot(RV, aes(x = Species)) +
geom_bar(aes(color = Species, fill = Species),
stat = "count", position = position_dodge(0.8),
width = 0.9)+
labs(y= "Count", x= "Species")
atsyplenkov
  • 1,158
  • 13
  • 25
  • 1
    check out `cowplot`. https://stackoverflow.com/questions/37335709/one-shared-legend-for-a-cowplot-grid-in-r – Ben Bolker Jul 19 '19 at 18:06
  • That didn't work unfortunately, I got the warning message 'Cannot convert object of class data.frame into a grob.' when I added the code plot_grid(SRG,U,CG,RV, align = 'h', labels = c('A','B','C','D')) – niamhailbhe Jul 19 '19 at 18:25
  • check `ggpubr` package and `ggarrange` function. See my answer here https://stackoverflow.com/a/60204246/9300556 – atsyplenkov Feb 13 '20 at 09:21

2 Answers2

0

You can try par(mfrow = c(2,2)

#Code 
 par(mfrow = c(2,2)
 #Code of Graph 1
 #Code of Graph 2
 #Code of Graph 3
 #Code of Graph 4
ealbsho93
  • 141
  • 4
0

Since all your data is in the same format you can combine the data frames with rbind.

combined_df <- rbind(SRG, CG, U, RV)

ggplot(combined_df, aes(x = Species)) +
geom_bar(aes(color = Species),
stat = "count", position = position_dodge(0.8),
width = 0.9)+
labs(y= "Count", x= "Species")
Sam
  • 341
  • 2
  • 10
  • That gives a total of the counts in all habitats. I want to plot all four habitats on graph. – niamhailbhe Jul 19 '19 at 19:34
  • In that case you can add a column to each dataframe rv <- cbind(rv, habitat=rv) then rbind then color = specoies:location in ggplot – Sam Jul 19 '19 at 19:53
  • That worked but it's too larger. The idea was to have a multi-facet graph with all four habitats shown individually with a common legend. Question has been edited. – niamhailbhe Jul 19 '19 at 22:33
  • OK then, cbind the habitats to each dataframe as above, then rbind the dataframes. In ggplot aes set color = species, and add +facet_wrap('habitat') to the end of the ggplot argument. – Sam Jul 19 '19 at 23:47