ggplot2: How do I rearrange the bars from highest to lowest?

Viewed 29

Data is in melted form currently, and shows percentages of each material type at two locations:

        Material   variable  value
1        Fishing       PP 54.045307
2           Rope       PP 10.679612
3  Packing_Strap       PP 10.032362
4       Industry       PP  4.207120
5       Domestic       PP  3.559871
6  Misc_Plastics       PP  2.912621
7   Unclassified       PP 14.563107
8        Fishing       CC 42.105263
9           Rope       CC 15.789474
10 Packing_Strap       CC  7.894737
11      Industry       CC  7.894737
12      Domestic       CC  0.000000
13 Misc_Plastics       CC  0.000000
14  Unclassified       CC 26.315789

So my current code looks like this:

ggplot(R_Edits.m, aes(x =reorder(variable, value), y = value, fill = Material)) + geom_bar(stat="identity", position ="Dodge", alpha=0.7) + theme_classic() + labs(x="Site", y="Percentage (%) Entanglements") + scale_y_continuous(expand = c(0,0)) + scale_fill_manual(values=c("cadetblue4", "#1F78B4", "#F46D43", "#CC79A7", "cadetblue3", "#33A02C", "#FF7F00")) + theme(axis.text.x = element_text(colour = "black")) + coord_flip()

Graph

I'm trying to rearrange the bars from highest to lowest, for each location (PP, CC). How do I achieve this? I have tried a few variations of "reorder" but so far no luck.

1 Answers

My suggestion would be using facet_grid instead to create the two sections of the graph and then each one inside allows the Material element to reorder by size:

df %>% 
ggplot(aes(x =reorder(Material, value), y = value, fill = Material)) +
  geom_bar(stat="identity", position ="Dodge", alpha=0.7) + 
  theme_classic() + 
  labs(x="Site", y="Percentage (%) Entanglements") +
  scale_y_continuous(expand = c(0,0)) + 
  scale_fill_manual(values=
                      c("cadetblue4", "#1F78B4", "#F46D43", 
                        "#CC79A7", "cadetblue3", "#33A02C", "#FF7F00")
                    ) +
  theme(axis.text.x = element_text(colour = "black")) + 
  facet_grid(variable ~ ., switch = "y") +
  theme(axis.text.y = element_blank(), 
        axis.ticks.y = element_blank(),
        strip.background = element_blank(),
        strip.placement = "outside"
        ) +
  coord_flip()

Created on 2020-12-01 by the reprex package (v0.3.0)

Related