0

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?

Community
  • 1
  • 1
verbati
  • 13
  • 3
  • You need to order the name factor. Possible duplicate of [this](http://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph) – Heroka Sep 02 '15 at 09:40
  • Would that solution still apply to a generic dataframe as opposed to table? If so, how? – verbati Sep 02 '15 at 09:44
  • Your `name` variable is the factor in this case. See this for more information: http://www.cookbook-r.com/Manipulating_data/Changing_the_order_of_levels_of_a_factor/ – hugot Sep 02 '15 at 09:49
  • vergatt, have a look at the bottom / last bit of code in Gavins answer at the link ... it explicitely shows how to do this – user20650 Sep 02 '15 at 09:54
  • @user20650, I think I understand it... but am having trouble applying it to his earlier code: levels=names(sort(table(Position), decreasing=TRUE)))) – verbati Sep 02 '15 at 09:56
  • Thanks for the solution – verbati Sep 02 '15 at 10:05

1 Answers1

1

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")
Community
  • 1
  • 1
verbati
  • 13
  • 3