0

I am trying to create a graph in ggplot2 with age-in-years-and-months on the x-axis. The age variable should look like this: "2;6" = 2 years and 6 months, "5;9" = 5 years and 9 months. The raw data for the x-axis consists of age in months, and a function is required to create the age-in-years-and-months variable. I have looked online, and while I can find plenty of material on plotting dates (e.g. using the "lubridate" package), I cannot work out how to adapt these routines to plot age. The ideal solution would be to relabel the x-axis using a custom function. Below is a minimal worked example. I've created a small dataset, a function to turn months into age-in-years-and-months, and I've begun the plot. Can anyone help me with the syntax for relabeling the x-axs (I think "scale-x-discrete" could be the right function). Thanks!

library(ggplot2)

# Create data frame
df <- cbind.data.frame(c(22.2, 24.3, 26.1, 39.8, 55.0), c(0.5, 0.6, 0.8, 1, 1.5))
names(df) <- c("age_months", "height")

# Create function for turning age-in-months into age-in-years+months
m2ym <- function(age_m){
  year <- floor(age_m/12)
  month <- floor(age_m - (year*12))
  return(paste0(year, ";", month))
}

#Now plot
g <- ggplot(df, aes(age_months, height))
g <- g + geom_point()
# Now add g <- g + scale_x_discrete()???
Nick Riches
  • 317
  • 2
  • 13
  • Possible duplicate: https://stackoverflow.com/q/37662119/3358272 (the point is not that that answer addresses "dates", the point is that you need to use `labels=` and create your `5;9` however you want with your data.) – r2evans Feb 13 '19 at 22:21

2 Answers2

2

You could add this at the end to get those custom labels:

my_breaks = 6*0:10  # every six months, from 0 to 60 months
my_breaks_labels = m2ym(my_breaks)  # save those numbers as "yr + mo" format
g + scale_x_continuous(breaks = my_breaks,         # use these breaks...
                       labels = my_breaks_labels)  # ...with these labels

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
1

I am not sure I fully understand the question and can't make a comment but from what I understand if you would like to plot your x axis using the function results instead, why not mutate a new column using your function, ie,

library(dplyr)
df <- df %>% mutate(age_y_m = m2ym(age_months))

then plotting the new column and relabelling the x axis

g <- ggplot(df, aes(x = age_y_m, y = height)) +
         geom_point() + 
         xlab("Age in Years and Months (y;m)")
Croote
  • 1,382
  • 1
  • 7
  • 15