willwudan (5) [Avatar] Offline
#1
Sorting the categories in a bar chart seems like a common task. Is there an easier way (like a one liner) to achieve the same as what is presented in Listing 3.10 (p. 50) with ggplot2? Thanks.
nina.zumel (17) [Avatar] Offline
#2
Re: Easier way to sort a bar chart? (p. 50)
In base plot, resorting the categories for this particular plot might be easier. In ggplot2, the order is determined by the order of the factors, so reordering the levels is the only way that I know of to put the categories in a different order. Unfortunately, I don't think there is a one-liner to do this.
willwudan (5) [Avatar] Offline
#3
Re: Easier way to sort a bar chart? (p. 50)
Here is my almost one-liner to reorder:

custdata$state.of.res <- factor(custdata$state.of.res, levels = names(sort(tapply(custdata$state.of.res, custdata$state.of.res, length))))



> In base plot, resorting the categories for this
> particular plot might be easier. In ggplot2, the
> order is determined by the order of the factors, so
> reordering the levels is the only way that I know of
> to put the categories in a different order.
> Unfortunately, I don't think there is a one-liner to
> do this.
kaveht (3) [Avatar] Offline
#4
Here is an alternate using dplyr to group the data and then using ggplot2:

# Alternate
state_order <- custdata %>%
group_by(state.of.res) %>%
summarise(count = n())
ggplot(state_order) + geom_bar(aes(x = reorder(state.of.res, count), y = count), stat = 'identity', fill ='grey') +
coord_flip() + xlab(label = "State of Residence") + ylab(label = "Count")
john.mount (79) [Avatar] Offline
#5
Thanks, that looks a good way to do it.