'Ordered bar plot with multiple groupings

Example data are here

I am struggling to create an ordered and grouped bar plot. Any assistance appreciated.

I have found two similar questions that essentially replicate what I am trying to produce but I cannot reproduce a similar plot myself. These questions are example 1 and example 2.

My code is as follows:

library(ggplot2); library(dplyr); library(tidyverse)

dput(n.bp.sp)
structure(list(Animal.group = c("Bird", "Bird", "Bird", "Bird", 
"Bird", "Bird", "Bird", "Bird", "Mammal", "Mammal", "Mammal", 
"Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
"Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
"Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
"Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
"Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
"Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
"Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
"Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
"Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Reptile"
), Family = c("Anatidae", "Columbidae", "Corvidae", "Corvidae", 
"Icteridae", "Laridae", "Passeridae", "Psittacidae", "Aplodontiidae", 
"Canidae", "Canidae", "Canidae", "Canidae", "Canidae", "Cricetidae", 
"Cricetidae", "Cricetidae", "Cricetidae", "Cricetidae", "Cricetidae", 
"Erinaceidae", "Felidae", "Geomyidae", "Geomyidae", "Geomyidae", 
"Geomyidae", "Geomyidae", "Geomyidae", "Geomyidae", "Hystricdae", 
"Leporidae", "Macropodidae", "Macropodidae", "Macropodidae", 
"Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", 
"Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", 
"Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", 
"Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Mustelidae", 
"Mustelidae", "Mustelidae", "Mustelidae", "Phalangeridae", "Procyonidae", 
"Sciuridae", "Sciuridae", "Sciuridae", "Sciuridae", "Sciuridae", 
"Sciuridae", "Sciuridae", "Spalacidae", "Suidae", "Urisidae", 
"Colubridae"), Scientific.name = c("Branta canadensis", "Columba livia domestica", 
"Coloeus monedula", "Corvus frugilegus", "Agelaius phoeniceus", 
"Larus argentatus", "Passer domesticus", "Myiopsitta monachus", 
"Aplodontia rufa", "Canis lupus", "Canis lupus dingo", "Canis lupus familiaris", 
"Canis simensis", "Vulpes vulpes", "Lasiopodomys brandtii", "Microtus arvalis", 
"Microtus californicus", "Microtus montanus", "Ondatra zibethicus", 
"Peromyscus maniculatus", "Erinaceus europaeus", "Felis catus", 
"Geomyidae spp.", "Geomys bursarius", "Thomomys bottae", "Thomomys mazma", 
"Thomomys monticola", "Thomomys spp.", "Thomomys talpoides", 
"Hystrix indica", "Oryctolagus cuniculus", "Macrcopus eugenii", 
"Macropus rufogriseus", "Thylogale billardierii", "Bandicota bengalensis", 
"Bandicota indica", "Gerbillurus paeba", "Golunda ellioti", "Meriones hurrianae", 
"Millardia gleadowi", "Millardia meltada", "Mus booduga", "Mus musculus", 
"Mus spp.", "Nesokia indica", "Rattus argentiventer", "Rattus exulans", 
"Rattus losea", "Rattus nitidus", "Rattus norgevicus", "Rattus norvegicus", 
"Rattus rattus", "Rattus spp.", "Rattus tiomanicus", "Tatera indica", 
"Unspecified rodent spp.", "Unspecified rodent spp.", "Mustela erminea", 
"Mustela furo", "Mustela nivalis", "Mustela spp.", "Trichosurus vulpecula", 
"Procyon lotor", "Cynomys gunnisoni", "Cynomys leucurus", "Cynomys ludovicianus", 
"Cynomys parvidens", "Funambulus tristriatus", "Otospermophilus beecheyi", 
"Urocitellus beldingi", "Spalax ehrenbergi", "Sus scrofa", "Ursus americanus", 
"Boiga irregularis"), Common.name = c("Canada goose", "Feral pigeon", 
"Western jackdaw", "Rook", "Red-winged blackbird", "European herring gull", 
"House sparrow", "Monk parakeet", "Mountain beaver", "Wolf", 
"Dingo", "Dog", "Ethiopian wolf", "Red fox", "Brandt's vole", 
"Common vole", "Califorian vole", "Montane vole", "Muskrat", 
"Eastern deer mouse", "European hedgehog", "Cat", "Geomyidae spp.", 
"Plains pocket gophers", "Botta's pocket gopher", "Mazama pocket gopher", 
"Mountain pocket gopher", "Thomomys spp.", "Northern pocket gopher", 
"Indian crested porcupine", "European rabbit", "Tammar wallaby", 
"Red-necked wallaby", "Tasmanian pademelon", "Lesser bandicoot rat", 
"Greater bandicoot rat", "Hairy-footed gerbil", "Indian bush rat", 
"Indian desert gerbil", "Sand-colored soft-furred rat", "Soft-furred rat", 
"Little indian field mouse", "House mouse", "Mus spp.", "Short-tailed bandicoot rat", 
"Ricefield rat", "Polynesian rat", "Lesser ricefield rat", "Himalayan field rat", 
"Brown rat", "Brown rat", "Black rat", "Rattus spp.", "Malayan field rat", 
"Indian gerbil", "unspecified rodent spp.", "Unspecified rodent spp.", 
"Stoat", "Ferret", "Weasel", "Mustela spp.", "Common brushtail possum", 
"Raccoon", "Gunnison's prairie dog", "White-tailed prairie dog", 
"Black-tailed prairie dog", "Utah prairie dog", "Jungle palm squirrel", 
"California ground squirrel", "Belding's ground squirrel", "Middle east blind mole-rat", 
"Feral pig", "American black bear ", "Brown treesnake"), n = c(1L, 
49L, 4L, 65L, 1L, 4L, 5L, 2L, 1L, 12L, 42L, 33L, 3L, 305L, 2L, 
4L, 1L, 1L, 1L, 3L, 1L, 144L, 3L, 3L, 15L, 2L, 15L, 8L, 37L, 
10L, 88L, 1L, 20L, 1L, 193L, 5L, 3L, 23L, 12L, 3L, 86L, 37L, 
237L, 64L, 79L, 16L, 16L, 4L, 23L, 6L, 90L, 273L, 58L, 17L, 81L, 
1L, 35L, 81L, 23L, 17L, 1L, 253L, 2L, 37L, 36L, 40L, 36L, 1L, 
16L, 2L, 3L, 41L, 5L, 76L)), row.names = c(NA, -74L), groups = structure(list(
    Animal.group = c("Bird", "Bird", "Bird", "Bird", "Bird", 
    "Bird", "Bird", "Bird", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", "Mammal", 
    "Reptile"), Family = c("Anatidae", "Columbidae", "Corvidae", 
    "Corvidae", "Icteridae", "Laridae", "Passeridae", "Psittacidae", 
    "Aplodontiidae", "Canidae", "Canidae", "Canidae", "Canidae", 
    "Canidae", "Cricetidae", "Cricetidae", "Cricetidae", "Cricetidae", 
    "Cricetidae", "Cricetidae", "Erinaceidae", "Felidae", "Geomyidae", 
    "Geomyidae", "Geomyidae", "Geomyidae", "Geomyidae", "Geomyidae", 
    "Geomyidae", "Hystricdae", "Leporidae", "Macropodidae", "Macropodidae", 
    "Macropodidae", "Muridae", "Muridae", "Muridae", "Muridae", 
    "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", 
    "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", 
    "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", "Muridae", 
    "Mustelidae", "Mustelidae", "Mustelidae", "Mustelidae", "Phalangeridae", 
    "Procyonidae", "Sciuridae", "Sciuridae", "Sciuridae", "Sciuridae", 
    "Sciuridae", "Sciuridae", "Sciuridae", "Spalacidae", "Suidae", 
    "Urisidae", "Colubridae"), Scientific.name = c("Branta canadensis", 
    "Columba livia domestica", "Coloeus monedula", "Corvus frugilegus", 
    "Agelaius phoeniceus", "Larus argentatus", "Passer domesticus", 
    "Myiopsitta monachus", "Aplodontia rufa", "Canis lupus", 
    "Canis lupus dingo", "Canis lupus familiaris", "Canis simensis", 
    "Vulpes vulpes", "Lasiopodomys brandtii", "Microtus arvalis", 
    "Microtus californicus", "Microtus montanus", "Ondatra zibethicus", 
    "Peromyscus maniculatus", "Erinaceus europaeus", "Felis catus", 
    "Geomyidae spp.", "Geomys bursarius", "Thomomys bottae", 
    "Thomomys mazma", "Thomomys monticola", "Thomomys spp.", 
    "Thomomys talpoides", "Hystrix indica", "Oryctolagus cuniculus", 
    "Macrcopus eugenii", "Macropus rufogriseus", "Thylogale billardierii", 
    "Bandicota bengalensis", "Bandicota indica", "Gerbillurus paeba", 
    "Golunda ellioti", "Meriones hurrianae", "Millardia gleadowi", 
    "Millardia meltada", "Mus booduga", "Mus musculus", "Mus spp.", 
    "Nesokia indica", "Rattus argentiventer", "Rattus exulans", 
    "Rattus losea", "Rattus nitidus", "Rattus norgevicus", "Rattus norvegicus", 
    "Rattus rattus", "Rattus spp.", "Rattus tiomanicus", "Tatera indica", 
    "Unspecified rodent spp.", "Mustela erminea", "Mustela furo", 
    "Mustela nivalis", "Mustela spp.", "Trichosurus vulpecula", 
    "Procyon lotor", "Cynomys gunnisoni", "Cynomys leucurus", 
    "Cynomys ludovicianus", "Cynomys parvidens", "Funambulus tristriatus", 
    "Otospermophilus beecheyi", "Urocitellus beldingi", "Spalax ehrenbergi", 
    "Sus scrofa", "Ursus americanus", "Boiga irregularis"), .rows = structure(list(
        1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 
        14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 
        25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 
        36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 
        47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56:57, 58L, 
        59L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, 
        70L, 71L, 72L, 73L, 74L), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, 73L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

n.bp.sp <- read.csv("test.csv", header = T)

n.bp.sp %>%
  arrange(Animal.group, desc(n)) %>%
  ggplot() + 
  aes(x = Family, y = n, fill = Animal.group) +
  geom_bar(stat = "identity")+
  scale_y_continuous(breaks = c(0, 250, 500, 750, 1000, 1250)) +
  theme_classic()+
  labs(x = "Family", y = "Number", fill = "Class") +
  theme(axis.title.x = element_text(face = "bold"),
        axis.title.y = element_text(face = "bold"),
        axis.text.x = element_text(angle = 45, hjust = 1),
        axis.text.y = element_text(),
        legend.title = element_text(face = "bold"))

This code produces this figure.

The correct figure should be grouped by Class and then otherwise the bars should be in descending order - essentially exactly the same as example 1 above.



Solution 1:[1]

ggplot automatically order alphabetically. If you want a different order, you can order the levels yourself.

df$Family <- factor(df$Family, levels = c("Muridae","Mustelidae",....))

I would also advise you to use facets to group the Classes: ggplot(...) + facet_wrap("~Animal.group")

# randomize the order
df$Family <- factor(cdfiao$Family,
                      levels = sample(unique(df$Family)))


ggplot(df, aes(x = Family, y = n, fill = Animal.group)) +
   facet_wrap("~Animal.group" ,,scales = "free_y", ncol =1) +
   geom_bar(stat = "identity")+
   scale_y_continuous(breaks = c(0, 250, 500, 750, 1000, 1250)) +
   theme_classic() +
   labs(x = "Family", y = "Number", fill = "Class") +
   theme(axis.title.x = element_text(face = "bold"),
       axis.title.y = element_text(face = "bold"),
       axis.text.x = element_text(angle = 45, hjust = 1),
       axis.text.y = element_text(),
       legend.title = element_text(face = "bold"))

Solution 2:[2]

The problem ended up being in the dataset itself - the dataset was at the level of n.bp.sp$Common.name, by grouping the dataset at the level of n.bp.sp$Family one of @fra previous answers then works fine.

Code below:

n.bp.f2 <- n.bp.sp %>% 
  group_by(Animal.group, Family) %>%
  summarise(n = sum(n))

n.bp.f2 %>%
  arrange(Animal.group, desc(n)) %>%
  mutate(Family = fct_inorder(Family)) %>%
  ggplot() + 
  aes(x = Family, y = n, fill = Animal.group)  +
  geom_bar(stat = "identity")+
  scale_y_continuous(breaks = c(0, 250, 500, 750, 1000, 1250)) +
  theme_classic()+
  labs(x = "Family", y = "Number", fill = "Class") +
  theme(axis.title.x = element_text(face = "bold"),
        axis.title.y = element_text(face = "bold"),
        axis.text.x = element_text(angle = 45, hjust = 1),
        axis.text.y = element_text(),
        legend.title = element_text(face = "bold"))

Correct final plot

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Pat Taggart