R在ggplot2的x轴上绘制年龄(以年和月为单位)

时间:2019-02-13 22:11:08

标签: r ggplot2 axes

我正在尝试在ggplot2中创建一个图表,在x轴上显示年月数。年龄变量应如下所示:“ 2; 6” = 2年零6个月,“ 5; 9” = 5年零9个月。 x轴的原始数据包含以月为单位的年龄,并且需要一个函数来创建“年岁和月份”变量。我在网上看过,虽然可以在绘制日期时找到很多资料(例如使用“ lubridate”程序包),但我无法弄清楚如何使这些例程适应绘制年龄。理想的解决方案是使用自定义函数重新标记x轴。下面是一个最小的工作示例。我创建了一个小的数据集,该函数可以将月份变成年复一年的年龄,并且已经开始绘制图表。谁能帮我重新标记x轴的语法(我认为“ scale-x-discrete”可能是正确的功能)。谢谢!

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

2 个答案:

答案 0 :(得分:2)

您可以在末尾添加此标签以获得这些自定义标签:

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

答案 1 :(得分:1)

我不确定我是否完全理解这个问题,也无法发表评论,但是根据我的理解,如果您想使用函数结果来绘制x轴,为什么不使用函数来修改新列,即,

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

然后绘制新列并重新标记x轴

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