Nick Riches
Nick Riches

Reputation: 411

R Plot age (in years and months) on the x-axis in ggplot2

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()???

Upvotes: 0

Views: 1350

Answers (2)

Jon Spring
Jon Spring

Reputation: 66970

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

Upvotes: 2

Croote
Croote

Reputation: 1424

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

Upvotes: 1

Related Questions