How to sort a horizontal bar-chart in descending order with ggplot?
Solution 1:
Update: I added some fake values for usd_pledged
since the column is not reconstructible:
library(forcats)
library(ggplot2)
library(dplyr)
df %>%
mutate(main_category = fct_reorder(main_category, usd_pledged)) %>%
ggplot(aes(x=main_category, y=usd_pledged, fill=main_category)) +
geom_col()+
coord_flip()
First answer:
I am not sure but I think you need geom_col
or geom_bar
Here is an example with the mtcars dataset:
- prepare
mtcars
to getcars
column andmpg
- use
fct_reorder
from forcats to ordercars
bympg
- use ggplot with
geom_col
- finally
coord_flip()
library(forcats)
library(ggplot2)
library(dplyr)
mtcars %>%
rownames_to_column("cars") %>%
select(cars, mpg) %>%
mutate(cars = fct_reorder(cars, mpg)) %>%
ggplot(aes(cars, mpg, fill=cars)) +
geom_col()+
coord_flip()