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

如何用R的ggplot绘制横坐标为姓名的年龄柱状图?

在ggplot2中绘制以姓名为横轴、年龄为纵轴的柱状图

问题原因与解决方案

你遇到的错误是因为geom_bar()默认使用stat_count()做计数统计,它仅需要x或y其中一个美学映射。而你的需求是直接用数据中已有的年龄值作为柱子高度,因此可以通过以下两种方式解决:

方法1:使用geom_col()

geom_col()是geom_bar(stat="identity")的简写,专门用于绘制已有数值的柱状图,代码如下:

age <- c(12, 13, 19, 10)
persons <- c("Luke", "William", "George", "Steven")
df <- data.frame(age, persons)

library(ggplot2)
ggplot(data = df, mapping = aes(x = persons, y = age)) + 
  geom_col()

方法2:在geom_bar()中指定stat="identity"

如果坚持使用geom_bar(),只需显式指定统计方法为identity,表示直接调用数据中的y值:

ggplot(data = df, mapping = aes(x = persons, y = age)) + 
  geom_bar(stat = "identity")

额外优化建议

  • 可以添加颜色、调整坐标轴标签,让图形更清晰:
ggplot(df, aes(x = persons, y = age, fill = persons)) +
  geom_col(show.legend = FALSE) +
  labs(x = "姓名", y = "年龄", title = "不同人员的年龄分布") +
  theme_minimal()
  • 如果想按年龄排序横轴姓名,可先对数据框排序:
df_sorted <- df[order(df$age), ]
ggplot(df_sorted, aes(x = reorder(persons, age), y = age, fill = persons)) +
  geom_col(show.legend = FALSE) +
  labs(x = "姓名", y = "年龄", title = "按年龄排序的人员年龄分布") +
  theme_minimal()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:30:56