Home > Mobile >  Order bars in descending order while showing percentages
Order bars in descending order while showing percentages

Time:10-31

I want to create a barchart that shows how often (in percentage) each 'type' of a categorical variable appears in the dataset. I want the bars to be ordered in descending order.

Using this reproducible example:

data <- chickwts %>%
  group_by(feed)

ggplot(data = data, )  
  geom_bar(aes(x = feed, y = stat(count)))

Now I would like the bars to be ordered in descending (or ascending) order, i.e., 'soybean' should be shown on the left, followed by 'casein', 'linseed' and 'sunflower', and 'horsebean' should be on the right.

enter image description here

CodePudding user response:

I would suggest you use geom_col after creating a column for counts.

Since I could not replicate your result(please provide a reproducible example next time), I made a simple example using the iris data set.

library(dplyr)
library(ggplot2)

#creating the data
data <- iris %>%
  group_by(Species) %>%
  summarise(mean_slength = mean(Sepal.Length)) %>%
  ungroup()

data
"# A tibble: 3 × 2
  Species    mean_slength
  <fct>             <dbl>
1 setosa             5.01
2 versicolor         5.94
3 virginica          6.59"

Then I simply plot a bar graph using the geom_col function. The code below will accidentally generate a graph in an ascending order.

ggplot(data = data, )  
  geom_col(aes(x = Species, y = mean_slength, fill = Species))

Let's create a graph in a descending order.

ggplot(data = data, )  
  geom_col(aes(x = reorder(Species, -mean_slength), y = mean_slength, fill = Species))

This will create a graph shuffling the x-axis in the descending order of the y-axis values.

I hope this helps and please choose my answer if it solved your problem. Thanks.

CodePudding user response:

I think I found a solution that works:

data <- chickwts %>%
  group_by(feed) %>%
  summarize(cnt=n()) %>%
  mutate(props = round(cnt / sum(cnt), 2))

ggplot(data = data, mapping = aes(x = reorder(feed, props), props))   
  geom_bar(stat = "identity")   coord_flip()

enter image description here

  • Related