Home > database >  Changing the order of a variable type displayed on ggplot
Changing the order of a variable type displayed on ggplot

Time:04-18

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

CodePudding user response:

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"))
  • Related