Search code examples
rfacet-wrapfacet-gridtidytext

scale_x_reordered does not work in facet_grid


I am a newbie in R and would like to seek your advice regarding visualization using reorder_within, and scale_x_reordered (library: tidytext).

I want to show the data (ordered by max to min) by states for each year. This is sample data for illustrative purposes.

test <- data.frame(stateabb = rep(state.abb, each = 5, times = 1), 
                   year = seq(2001,2005,1),
                   value = sample(1:100, 250, replace = TRUE))

I successfully created the simple chart by state and year by using the following code.

ggplot(test, aes(x = stateabb, y = value)) +
    geom_bar(stat = "identity") +
    facet_grid(year ~ ., scales = "free_x")

enter image description here

Looking at this chart, it is very hard to see which State is the best in each year. So, I decided to order the value each year by using reorder_within.

ggplot(test, aes(x = reorder_within(stateabb, -value, year), y = value)) +
    geom_bar(stat = "identity") +
    facet_grid(year ~ ., scales = "free_x") + 
    scale_x_reordered()

enter image description here However, I could not show it as I did in the first picture. I thought scale_x_reordered could solve it, but it did not turn out as I expected. I also understand that I need to set the x-axis free in order to show the order of states in each year. But doing that does not get me anywhere. What did I do wrong here? Is there any other appropriate way to show the order of these states by year? Any suggestions or advice to show this chart properly would be appreciated. Thank you so much ahead of time!


Solution

  • This can't work, because facet_grid would only have one shared x-axis. But the orders are different in every facet. You want facet_wrap. For example like this:

    library(ggplot); library(tidytext)
    ggplot(test, aes(x = reorder_within(stateabb, -value, year), y = value)) +
        geom_bar(stat = "identity") + scale_x_reordered() +
        facet_wrap(year ~ ., ncol = 1, scales = "free_x", strip.position = "right")
    

    enter image description here