1

I wanted to move my bars according to this particular order for the beetle number i.e., from 0 to 1-5 to 6-10 to 11-15 to Above 15. I also wanted to place Village first and the Municipality. The plots should also be arranged in terms of the age of the building. Under 5 years first, then 5-10 years followed by Above 10 years

ggplot(g,aes(x=Locality.Division))+
  geom_bar(aes(fill=Number.of.Beetle),position="dodge")+
  facet_wrap(~Building.Age)
#> Error in ggplot(g, aes(x = Locality.Division)): could not find function "ggplot"

Created on 2021-05-30 by the reprex package (v2.0.0)

  • Call the `ggplot2` package using `library(ggplot2)` before you run the code. Please also visit [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – UseR10085 May 30 '21 at 11:48
  • Does this answer your question? [Error: could not find function ... in R](https://stackoverflow.com/questions/7027288/error-could-not-find-function-in-r) – user438383 May 30 '21 at 11:50

2 Answers2

1

I hope the following helps to get you started. You did not provide a minimal reproducible example, thus, I simulate some data. I also adapted the variable names. A key strategy to control the order of variables is making them a factor. I do this when plotting.

Note: number of beetles is quasi-sorted given the values used. Here you could also work with a factor, if needed.

library(ggplot2)

set.seed(666)   # fix random picks for replicability

# simulate data of 30 buildings
df <- data.frame(
    Building = 1:30
  , Building.Age = sample(x = c("U5","5-10","A10"), size = 30, replace = TRUE)
  , Nbr.Beetle   = sample(x = c("1-5","6-10","11-15","15+"), size = 30, replace = TRUE)
  , Locality     = sample(x = c("A","B","C"), size = 30, replace = TRUE))

# plot my example
ggplot(data = df, aes(x=Locality)) +
  geom_bar(aes(fill=Nbr.Beetle),position="dodge") +
# --------------------- control the sequence of panels by forcing level sequence of factor
  facet_wrap(. ~ factor( Building.Age, levels = c("U5","5-10","A10") ) )

This yields:

enter image description here

Ray
  • 2,008
  • 14
  • 21
1

The order of the bars is determined by the order of the factor levels of the variable.

You have the Number.of.Beetle variable in your data a character variable. ggplot() converts this to a factor variable with factor(), which by default sorts character variables alphabetically. To specify a different order, convert the variable to a factor yourself before plotting:

g <- mutate(g,
  Number.of.Beetle = factor(Number.of.Beetle, levels = c("1-5", "6-10", "11-15", "15+))
)

If the order is shown backwards, then also use forcats::fct_rev() to reverse the order:

g <- mutate(g,
  Number.of.Beetle = forcats::fct_rev(factor(Number.of.Beetle, levels = c("1-5", "6-10", "11-15", "15+)))
)
Brenton M. Wiernik
  • 1,006
  • 4
  • 8