0

I'm trying to generate a bar chart (using ggplot2) with location estimates data along the y axis and a basic count scale along the x axis. My data is structured like so:

  Data <- data.frame(locations = c("A","B","C","D"...), estimates = c(200, 300, 400, 200...)

I then used dplyr to arrange my data according to estimates

  library(dplyr)
  Data <- Data %>% arrange(estimates)

So then I run my ggplot2 code

  library(ggplot2)
  ggplot(Data, aes(locations, weight = estimates))+
         geom_bar()+
         coord_flip()

But the resulting plot is such, the bars have not been ordered according to estimates.

enter image description here

pogibas
  • 25,773
  • 19
  • 74
  • 108
Pryore
  • 490
  • 8
  • 21

1 Answers1

1

There's no point using dplyr. All you have to do is to order estimates, extract corresponding locations and pass it to scale_x_discrete, for example: scale_x_discrete(limits = Data$locations[order(Data$estimates)])

library(ggplot2)

 ggplot(Data, aes(locations, weight = estimates))+
         geom_bar()+
         coord_flip() +
         scale_x_discrete(limits = Data$locations[order(Data$estimates)])

enter image description here

pogibas
  • 25,773
  • 19
  • 74
  • 108