0
votes

I find countless examples of reordering X by the corresponding size of Y if the Dataframe for ggplot2 (geom_bar) is read using stat="identity".

I have yet to find an example of stat="count". The reorder function fails as I have no corresponding y.

I have a factored DF of one column, "count" (see below for a poor example), where there are multiple instances of the data as you would expect. However, I expected factored data to be displayed:

ggplot(df, aes(x=df$count)) + geom_bar() 

by the order defined from the quantity of each factor, as it is different for unfactored (character) data i.e., will display alphabetically.

Any idea how to reorder?

This is my current awful effort, sadly I figured this out last night, then lost my R command history: enter image description here

2
Would you be able to add some example data and the output that you get / expect?Vlad C.
I'm trying to put up some data, it's over a remote connection so I can't actually copy&paste.Anthony Nash

2 Answers

0
votes

Converting the counts to a factor and then modifying that factor might help accomplish what you need. In the below I'm reversing the order of the counts using fct_rev from the forcats package (part of tidyverse)

library(tidyverse)
iris %>%
  count(Sepal.Length) %>% 
  mutate(n=n %>% as.factor %>% fct_rev) %>% 
  ggplot(aes(n)) +  geom_bar()

Alternatively, if you'd like the bars to be arranged large to small, you can use fct_infreq.

iris %>%
  count(Sepal.Length) %>% 
  mutate(n=n %>% as.factor %>% fct_infreq) %>% 
  ggplot(aes(n)) +  geom_bar()
0
votes

If you start off your project with loading the tidyverse, I suggest you use the built-in tidyverse function: fct_infreq()

ggplot(df, aes(x=fct_infreq(df$count))) + geom_bar()

As your categories are words, consider adding coord_flip() so that your bars run horizontally.

ggplot(df, aes(x=fct_infreq(df$count))) + geom_bar() + coord_flip()

This is what it looks like with some fish species counts: A horzontal bar chart with species on the y axis (but really the flipped x-axis) and counts on horizontal axis (but actually the flipped y-axis). The counts are sorted from least to greatest.