You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言Age列月份转年份及儿童身高性别ggplot可视化问题咨询

解决方法

将以月份为单位的Age字段转换为以年为单位,仅需将字段值除以12即可,你可以直接修改绘图时的x轴映射,也可以提前预处理数据集新增字段,两种实现方式如下:


方法1:直接在绘图映射中转换单位

无需修改原数据集,仅调整ggplot的x轴映射逻辑即可,完整代码:

library(Stat2Data)
library(ggplot2)
data("Kids198")
glimpse(Kids198)

kidsGraph <- 
  ggplot(data = Kids198,
         aes(
         x = Age / 12, # 月份转年份,直接除以12
         y = Height,
         color = as.factor(Sex),
         )) +
  ggtitle("Boys and Girls Height by Age"
         ) +
  scale_color_manual(
    values = c("Orchid", "Dark Blue"), 
    name = "Gender", 
    labels = c("Female", "Male")
    ) +
  labs(
    x = "Age (years)",
    y = "Height (inches)"
  ) +
  scale_x_continuous() +
  theme_classic() +
  geom_point() +
  geom_smooth()
  
kidsGraph

方法2:提前预处理数据集新增年龄字段

如果后续需要多次使用以年为单位的年龄字段,可以提前在数据集中新增对应列:

library(Stat2Data)
library(ggplot2)
library(dplyr)
data("Kids198")

# 新增以年为单位的年龄字段
Kids198 <- Kids198 %>% 
  mutate(age_years = Age / 12)

kidsGraph <- 
  ggplot(data = Kids198,
         aes(
         x = age_years,
         y = Height,
         color = as.factor(Sex),
         )) +
  ggtitle("Boys and Girls Height by Age"
         ) +
  scale_color_manual(
    values = c("Orchid", "Dark Blue"), 
    name = "Gender", 
    labels = c("Female", "Male")
    ) +
  labs(
    x = "Age (years)",
    y = "Height (inches)"
  ) +
  # 可自定义x轴刻度间隔,示例为每1年显示一个刻度
  scale_x_continuous(breaks = seq(2, 18, 1)) +
  theme_classic() +
  geom_point() +
  geom_smooth()
  
kidsGraph

内容的提问来源于stack exchange,提问作者hopefullyphdsoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:48:01