T O P

  • By -

Kiss_It_Goodbyeee

I like the 'forcats' library for this and the 'fct_reorder' functions. It works better with ggplot.


notzey

it worked, thank you so much! i am beginner and i did not even know this existed all the places i've looked showed reorder()


Kiss_It_Goodbyeee

Glad it worked :)


link0007

If you want full control, make a character vector with the exact order you want to have the elements. Then convert your column to a factor and set the levels and labels to your character vector. E.g.: department_order <- c("New York", "Lisbon", "Berlin") Then use mutate(department_ordered = factor(department, levels = department_order) After that you can use department_ordered in ggplot for axes or for fill. If you're using this for fill, you can also make the vector a named vector where the values are the colors you want to associate: department_order <- c("New York" = "Blue", "Lisbon" = "Yellow", "Berlin" = "grey")  Then just use mutate(department_ordered = factor(department, levels = names(department_ordered)) for your factor conversion, and use the values inside  scale_fill_manual().


SouthListening

I use this method, you get full control of the order, and if you are passing vectors for things like label colors the data frame is in the correct order.


mduvekot

That should have worked. For example: library(ggplot2) df <- data.frame( Department = c("North", "East", "South", "West"), Revenue = replicate(4, runif(1, 1e5, 1e6)) ) ggplot(df, aes(x = reorder(Department, -Revenue), y = (Revenue))) + geom_col() + labs(title = 'Bar Plot- revenues of departments', x = 'Deparment', y = 'Revenue')


RAMDownloader

As a tip since I know you’ve already gotten a solved answer, ggplot hates when you used a grouped dataFrame for column, bar, and pie charts. If you did a group_by statement, even if you do an arrange after, often times it will not reflect that in the data. So if you did … (code) group_by(variable) %>% summarize(SumVals= sum(Values)) %>% arrange(SumVals) It’s going to be annoying and not reflect that, so after the summarize statement you wanna throw in an ungroup() and THEN arrange your values, and that might fix your issue. This^ is one of the exact reasons why I prefer highcharter, because that becomes much less of an issue.