verbati
verbati

Reputation: 13

Keeping order for ggplot bar chart in R

I have the following ordered dataframe df:

                                  name freq
14                          John Smith   35
18                          Oliver White 23
15                     Wayland Johnson   12
19                          Joey Black    9

However when I plot in ggplot the order is not kept. Here is my ggplot code:

m <- ggplot(c_sorted, aes(x=name, y=freq))
m + geom_bar(stat = "identity")

Would I have to order it again in the ggplot code?

With regards to a possible duplicate of:

Order Bars in ggplot2 bar graph

How would I implement that solution for a dataframe? What would be the factor?

Upvotes: 0

Views: 945

Answers (1)

verbati
verbati

Reputation: 13

I found a straightforward answer on this page:

Plot data in descending order as appears in data frame

Without using factors, you can just reorder within the ggplot code:

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

Upvotes: 1

Related Questions