1
votes

I am new here in stackoverflow and also new in R. I have a question. How do you sort data using ggplot and geom_bar in descending order? Here is my code:

ggplot(actions) +geom_bar(mapping=aes(x=reorder(Actions,Actions,length))) +coord_flip() + ylab("Count") +xlab("Actions")

Here is the output. Would be very grateful for your help. Thank you!

enter image description here

1
Welcome to SO, Please see this first how-to-ask SO is a platform where you can get a good suggestion regarding your problems. But for that, you need to be more specific about what you are asking? what have you done so far? Before asking please see the suggested SO question and take a look at them. Still, you did not find a solution then you can ask a question here.ankit suthar
aes(x=reorder(Actions, Actions, function(x)-length(x)))AK88

1 Answers

2
votes

You need to reorder your dataframe based on you chosen axis. Here is a working example with cars dataset.

df <- mtcars

df2 <- transform(df,
          cyl = reorder(cyl,order(mpg, decreasing = TRUE)))

p <- ggplot(df2) + 
                geom_bar(aes(x = cyl, y = mpg), stat = 'identity') +
                coord_flip() + 
                ylab("mpg") +
                xlab("cyl")

print(p)

Sorted based on cyl, as that was on my x-axis originally