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

如何用ggplot绘制带月份名称的年月组合x轴脑卒中患者直方图?

实现年月组合x轴的直方图方案

要实现x轴按「2005年1月、2005年2月……」顺序显示并带月份名称的直方图,只需将年份和月份组合成格式化的时间标签,再按时间顺序排列即可,以下是具体代码:

方法一:使用lubridate包(推荐,处理日期更便捷)

# 安装并加载所需包(首次使用需安装)
# install.packages(c("lubridate", "ggplot2"))
library(lubridate)
library(ggplot2)

# 1. 将Year和Month组合为日期格式列
stroke$date <- ymd(paste(stroke$Year, stroke$Month, "01", sep = "-"))

# 2. 生成带中文年月的标签(如"2005年1月")
# 若要显示中文月份全称(如"2005年一月"),可替换为:format(stroke$date, "%Y年%B", locale = "zh_CN.UTF-8")
stroke$date_label <- format(stroke$date, "%Y年%m月")

# 3. 绘制直方图,确保x轴按时间顺序排列
ggplot(stroke, aes(x = reorder(date_label, date), y = stroke_victims)) +
  geom_bar(stat = "identity") +
  labs(title = "2005-2007年每月中风患者数量", x = "年月", y = "中风患者数") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 旋转标签避免重叠

方法二:基础R实现(无需额外包)

library(ggplot2)

# 1. 直接生成年月标签
stroke$date_label <- paste(stroke$Year, "年", stroke$Month, "月", sep = "")

# 2. 按年份和月份对数据框排序,保证x轴顺序正确
stroke <- stroke[order(stroke$Year, stroke$Month), ]

# 3. 绘制直方图
ggplot(stroke, aes(x = date_label, y = stroke_victims)) +
  geom_bar(stat = "identity") +
  labs(title = "2005-2007年每月中风患者数量", x = "年月", y = "中风患者数") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

关键说明

  • reorder(date_label, date)(方法一中)用于确保x轴按时间顺序排列,而非标签的字母顺序
  • 旋转x轴标签的theme设置可根据实际情况调整角度,提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:51:13