1

I have created a barchart in R studio using dplyr. The bars are not in the right order. Kindly help me reorder 0,1-5,6-10,11-15 and Above 15 I have used the following code to create the chart

BarChart(Number.of.Beetle, 
         data = g, 
         by1 = Locality.Division, 
         main = "Beetle number vs Locality Division" , 
         xlab = "Number of beetle" , 
         ylab = "Locality Division")

image

Martin Gal
  • 16,640
  • 5
  • 21
  • 39
  • If you provide a reproducible part of your dataset, it would be easier to solve your issue.(in dput format prefered). – Behnam Hedayat May 26 '21 at 15:39
  • I'm not familiar with the BarChart() function, and it's not part of base R. Can you also include what package contains this function? If it's well behaved, BarChart() should pay attention to the order of the Locality.Division factor. See this SO answer for how to order a factor for plotting. https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph – blongworth May 26 '21 at 15:49

1 Answers1

2

I think this is what you want:

library(dplyr)
library(ggplot2)
library(tibble)

##----------------------------------------
## Creating a dataset to simulate yours
##----------------------------------------

df <- tibble(
  beetle = sample(0:25, 500, replace = TRUE),
  loclity_division = sample(c("Municipality", "Village"), 500, replace = T),
)

df$beetle <-  ifelse(df$beetle > 1 & df$beetle <= 5, "1-5",
              ifelse(df$beetle > 5 & df$beetle <= 10, "6-10",
              ifelse(df$beetle > 10 & df$beetle <= 15, "11-15",
              ifelse(df$beetle > 15, "Above 15", "0"
              ))))


##--------------------------------------
## Determine the custom order of levels
##--------------------------------------

df$beetle <- factor(df$beetle, levels = c("0", "1-5", "6-10", "11-15", "Above 15"))


##----------------------
## Plotting by ggplot
##----------------------

df %>%
  ggplot(aes(x = beetle, fill = beetle)) +
    geom_bar(width = 0.6) + 
    coord_flip() + 
    facet_wrap(vars(loclity_division))

enter image description here

Behnam Hedayat
  • 837
  • 4
  • 18