I'm wondering if there's a way of changing the fill order of a faceted histogram based on some variable.
For example, let's say I'm studying how fast animals are, and whether that's correlated with them being good or bad.
I'll generate some data to this effect:
library(tidyverse)
# generate animal info
df_a <- tibble(speed = .75 * runif(400)) %>%
mutate(animal = "cat", goodness = "bad")
df_b <- tibble(speed = .75 * runif(100)) %>%
mutate(animal = "cat", goodness = "good")
df_c <- tibble(speed = runif(400)) %>%
mutate(animal = "dog", goodness = "good")
df_d <- tibble(speed = runif(100)) %>%
mutate(animal = "dog", goodness = "bad")
# bind data into one df
df <- bind_rows(df_a, df_b, df_c, df_d) %>%
mutate_if(is.character, as.factor)
# plot df
df %>%
ggplot(aes(x = speed)) +
geom_histogram(aes(fill = animal),
breaks = seq(0,1, by = .05),
alpha = .75, position = "identity") +
coord_flip() +
facet_wrap(~ goodness) +
ggtitle("Are good pets faster?")
I get something like:
In this example, everyone can see the distribution of bad animals very easily, whereas the good cats fade into the background.
If I were to supplement my data with some sort of factor, would there be a way to key this factor to the order in which the histogram would draw its fill
parameter? e.g. can I make cats be in the background for my first plot, but dogs be in the background for the second plot?
I am not interested in stacking the histogram data with the position = "stacked"
option.
Thanks for your help!