0

as you can see on my x-axis, I need to move the position of the axis label "5 to 9" together with its bar column in front, after "0 to 4". Below is my code. enter image description here

library(ggplot2)

ggplot(age, aes(factor(age), case, fill = sex)) + 
  geom_bar(stat="identity") + 
  scale_fill_brewer(palette = "Set1")+
  ylab("# Cases") +
  xlab("Age") +
  theme(axis.text = element_text(size = 13)) +
  theme(axis.title = element_text(size = 14)) 
Ella Taib
  • 63
  • 4
  • Please `dput(age)` and add to the post! – Duck Aug 04 '20 at 17:19
  • 1
    It's right where it "should" be: because those labels are all strings, they are being sorted alphabetically (without regard to numeric content). Use a `factor` to force the order, and `ggplot2` will do what you want. (There are plenty of questions on SO about reordering labels or facets or what-have-you ... and they all end up recommending `factor` and manually controlling the `levels=` of them.) – r2evans Aug 04 '20 at 17:29

1 Answers1

1

you could try this on your data frame (Age?):

library(tidyverse)

Age <- Age %>% 
  mutate(age  = fct_relevel(age, "0 to 4", "5 to 9", "10 to 14"))

..but it is possible that you have to take ap all your levels in this list, so it may be not ideal

BeccaLi
  • 174
  • 7