Best way to order ggplot barplot

I'm plotting a simple barplor using ggplot2 using data from the "Digital News Report". Here's my data:

media <- c("Online", "TV", "Print", "Social Media")
perc <- c(89,75,40,71)
data <- data.frame(cbind(media,perc))

And here's my plot

library(tidyverse)

ggplot(data, aes(media,perc))+
  geom_bar(stat = "identity")+
  coord_flip()+
  theme_classic()

I want to order it in a decreasing way and I can do it like this:

data$media <- factor(data$media, levels = c('Print','Social Media','TV', 'Online'))

But I'm lookinf for a faster way to do it (especially when I've to work with more categories).

Hi @TomasG,

Try this:

library(tidyverse)
  
media <- c("Online", "TV", "Print", "Social Media")
perc <- c(89,75,40,71)
data <- data.frame(cbind(media,perc))

data %>% 
  ggplot(aes(fct_reorder(media, perc), perc)) +
  geom_col() +
  coord_flip() +
  theme_classic()
1 Like

It works fine, I just had to transform the variable to numeric.

Thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.