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

如何在R语言中绘制直方图?求助添加‘Age at visit’列方法

在R语言中绘制带'Age at visit'列的直方图

1. 创建'Age at visit'字段

假设你的数据框名为df,包含出生年份(比如birth_year)和就诊年份(比如visit_year)字段,就诊年龄的计算逻辑就是用就诊年份减去出生年份,以下是两种常用实现方式:

基础R实现

# 直接在数据框中新增列
df$`Age at visit` <- df$visit_year - df$birth_year

dplyr管道实现(更适合批量数据处理)

先加载dplyr包(属于tidyverse工具集):

library(dplyr)
df <- df %>%
  mutate(`Age at visit` = visit_year - birth_year)

2. 绘制类似参考图的直方图

参考图呈现的是分组式的年龄分布,这里假设你需要按分类变量(比如性别gender)分组展示,用ggplot2包实现:

首先加载ggplot2:

library(ggplot2)

分组频率直方图(与参考图结构一致)

ggplot(df, aes(x = `Age at visit`, fill = gender)) +
  geom_histogram(binwidth = 5, alpha = 0.7, position = "dodge", color = "black") +
  labs(title = "Age at Visit Distribution",
       x = "Age at Visit",
       y = "Frequency",
       fill = "Gender") +
  theme_bw()

参数说明

  • binwidth = 5:设置直方图组距为5岁,可根据数据分布调整
  • alpha = 0.7:设置分组填充色透明度,避免重叠遮挡
  • position = "dodge":让分组直方图并排显示,改为position = "stack"可堆叠展示
  • theme_bw():切换为简洁的黑白主题,更符合学术图表风格

额外处理提示

如果你的年份字段是字符型,需要先转换为数值型:

df$birth_year <- as.numeric(df$birth_year)
df$visit_year <- as.numeric(df$visit_year)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 11:04:59