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

ggplot技术问询:如何用柱状图展示mpg数据集class对应的cty与hwy均值

问题解决与说明

1. 实现cty和hwy均值的柱状图可视化

你的代码问题出在数据格式和映射逻辑上:ggplot需要将cty和hwy这两个变量转为长格式,才能把它们作为分组(fill)来展示各自的均值。当前宽格式下,你只映射了y=cty,fill=hwy是连续数值,无法生成对应分组的柱形。

方法一:转换数据格式后用stat_summary绘图

library(tidyverse)
data("mpg")

# 把宽格式转长格式,合并cty和hwy为同一列,标记变量类型
mpg_long <- mpg %>%
  pivot_longer(cols = c(cty, hwy), names_to = "metric", values_to = "efficiency")

# 绘制分组柱状图,展示每个class下cty和hwy的均值
ggplot(mpg_long, aes(x = class, y = efficiency, fill = metric)) +
  geom_bar(stat = "summary", fun = "mean", position = position_dodge(width = 0.8)) +
  labs(title = "不同车型的城市/高速油耗均值", x = "车型类别", y = "油耗均值", fill = "油耗类型")

方法二:先手动汇总数据再绘图(更直观可控)

如果想明确看到汇总后的数值,可以先计算均值,再用geom_col(适合预先汇总好的数据,无需额外stat参数):

mpg_summary <- mpg %>%
  group_by(class) %>%
  summarise(
    cty_mean = mean(cty),
    hwy_mean = mean(hwy)
  ) %>%
  pivot_longer(cols = c(cty_mean, hwy_mean), names_to = "metric", values_to = "efficiency")

ggplot(mpg_summary, aes(x = class, y = efficiency, fill = metric)) +
  geom_col(position = position_dodge(width = 0.8)) +
  labs(title = "不同车型的城市/高速油耗均值", x = "车型类别", y = "油耗均值", fill = "油耗类型")

2. 关于ggplot的详细参考资料

  • 官方权威书籍:《ggplot2: Elegant Graphics for Data Analysis》(第二版),由ggplot2开发者Hadley Wickham编写,系统讲解了ggplot的图层语法、所有核心组件(geom、stat、scale、theme等)的逻辑和参数,是最全面的参考资料。
  • 内置帮助的深度用法:每个geom/stat的帮助页面(比如输入?geom_bar、?stat_summary)包含所有参数的详细说明及示例代码。比如想了解stat参数的可选值,可查看对应统计变换函数的文档(如?stat_summary、?stat_identity)。
  • 内置教程文档:在R控制台输入browseVignettes("ggplot2"),可查看ggplot2自带的分步教程,覆盖从基础到进阶的各类场景。

内容的提问来源于stack exchange,提问作者Bernát Kun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:47:12