'Changing the order of a variable type displayed on ggplot

This is my first post so apologies if it is not explained in the best of ways, I will improve. I have created a line graph with ggplot2 that shows the number of cases for a specific disease per age category over a couple of months.

 df %>% 
      ggplot(aes(x = Month, y = Count, group = Category, color = Category)) +
      geom_point() +
      geom_line()

Category variable consists of the following types: "1-10", "11-16", "17-24", "25-30", "30 and over"

Unfortunately, one of the type of age category is not displayed in the correct order. I have 1-10, 17-24, 25-30, 11-16, 30 and over. How do I shift the 11-16 category so that it appears on the chart and in the description just after the 1-10 category? Also - is there a way to define what how many months are labeled on the x axis? Currently I see the trend line for each age category, but I only see the labels for three of the months. This is not a massive problem given the purpose of this graph but it might be useful in the future.

Many thanks for all your help in advance - much appreciated



Solution 1:[1]

I suspect that you need to convert Category into an ordered factor, as such:

df$Category <- factor(df$Category, levels = c("1-10", "11-16", "17-24", "25-30", "30 and over"))

or with tidyverse:

df_final <- df %>% mutate(Category = factor(Category, levels = c("1-10", "11-16", "17-24", "25-30", "30 and over"))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nick Camarda