簡體   English   中英

R在ggplot2的x軸上繪制年齡(以年和月為單位)

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

我正在嘗試在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()???

您可以在末尾添加此標簽以獲得這些自定義標簽:

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

在此處輸入圖片說明

我不確定我是否完全理解問題並且無法發表評論,但是從我的理解中,如果您想使用函數結果來繪制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)")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM