I have a question, how can you order the bars using facet_wrap()
.
library(dplyr)
library(tidyr)
library(ggplot2)
iris %>% gather(medida, valor, -Species) %>%
ggplot(aes(reorder(Species, valor), valor, fill=reorder(Species, valor))) +
geom_col() +
facet_wrap(~ medida, scales = "free")+
theme(legend.position = "none")
You can see that the bars in the last group are not ordered. How could you order them?
There is a solution for that problem in the library
tidytext
. It's a bit weird that it's in a natural language processing library and not in an extension toggplot2
, it happens to be a recurring problem when graphing word counts.It is about two functions that work together:
reorder_within()
that it allows reordering for more than one variable andscale_x_reordered()
that it is a scale soggplot2
that it understands those reorderings.Your case is covered in the help of
scale_x_reordered()
, I'm just adapting it, I haven't even changed the names.The result:
The problem occurs because reorder generates an ordered factor se
Species
, but orders it from highest to lowest overall, that is, within all groups. Thenvirginica
, the one that has the highest value among all the groups is considered greater and the information that in the groupSepal.Width
the highest value has it is lostsetosa
.The solution of
tidytext
is to order groups with the two variables. You can see the behavior by using the function inside amutate
before plotting rather than directly in the call ofggplot
. Andscale_x_reordered()
then split that column into two and apply the reordering within each group. It's actually a not very elegant workaround, but it works...