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

如何用R语言ggplot绘制每月平均租金的柱状图?

解决每月平均租金柱状图绘制问题

问题分析

你的代码存在几个核心问题:

  • ggplot的aes映射中不能直接传入mean(Rent),y轴需映射原始数据,再通过统计逻辑计算均值
  • as.Date(Posted.On)未指定日期格式,原数据是mm/dd/yyyy格式,默认解析规则会导致日期识别错误
  • geom_bar()默认是对数据计数,而非计算指定字段的均值

解决方案

方法1:先预处理数据再绘图

先分组计算每月平均租金,再用处理后的数据集绘图,逻辑更清晰:

# 加载依赖包
library(ggplot2)
library(lubridate)

# 转换日期格式并提取月份名称(label=TRUE会生成英文月份名)
data$Month <- month(as.Date(data$Posted.On, format = "%m/%d/%Y"), label = TRUE)

# 分组计算每月平均租金
monthly_avg_rent <- aggregate(Rent ~ Month, data, mean)

# 绘制柱状图
ggplot(monthly_avg_rent, aes(x = Month, y = Rent)) +
  geom_col(fill = "steelblue") +
  labs(title = "每月平均租金", x = "月份", y = "平均租金") +
  theme_minimal()

方法2:直接在ggplot中用stat_summary计算均值

无需提前汇总数据,直接通过stat_summary内置逻辑计算并绘制均值:

library(ggplot2)
library(lubridate)

# 转换日期格式并提取月份名称
data$Month <- month(as.Date(data$Posted.On, format = "%m/%d/%Y"), label = TRUE)

# 绘制柱状图
ggplot(data, aes(x = Month, y = Rent)) +
  stat_summary(fun = mean, geom = "col", fill = "steelblue") +
  labs(title = "每月平均租金", x = "月份", y = "平均租金") +
  theme_minimal()

关键细节说明

  • 若需要中文月份名,可给month()函数加参数locale = "zh_CN.UTF-8"(需确保系统支持中文本地化配置)
  • geom_col()用于绘制基于数值的柱状图,区别于默认计数的geom_bar(),是这类场景的正确选择
  • 必须指定as.Date的format = "%m/%d/%Y",否则会因日期解析错误导致后续月份提取失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:30:53