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

如何用ggplot绘制以Year为X轴的分类变量填充柱状图?

用ggplot绘制指定柱状图的方法

首先确保你已安装并加载包含ggplot2的tidyverse包:

# 未安装则执行此句
install.packages("tidyverse")
# 加载包
library(tidyverse)

先将你提供的数据导入R环境:

trade_data <- structure(list(Year = c(1986L, 1994L, 1995L, 1996L, 1997L, 1998L, 
1999L, 2000L, 2001L, 2002L, 2003L, 2004L, 2005L, 2006L, 1994L, 
1995L, 1996L, 1997L, 1998L, 1999L, 2000L, 2001L, 2002L, 2003L, 
2004L, 2005L, 2006L), Commodity.Code = c(84L, 84L, 84L, 84L, 
84L, 84L, 84L, 84L, 84L, 84L, 84L, 84L, 84L, 84L, 85L, 85L, 85L, 
85L, 85L, 85L, 85L, 85L, 85L, 85L, 85L, 85L, 85L), Trade.Value = c(152775, 
2832605, 18315000, 25698163, 27913535, 30960755, 39638469, 47361219, 
48195570, 989056362, 2561299092, 2757388123, 2921517723, 3445065950, 
81496, 3621489, 42467420, 101764359, 121149310, 155909559, 124826429, 
132251188, 239727925, 349458661, 506121578, 768955783, 1034644162
)), class = "data.frame", row.names = c(NA, -27L))

根据需求,这里提供两种常见的柱状图展示方式:

1. 分组柱状图(并列展示同年份不同商品)

适合对比同一年份下不同商品的交易额:

ggplot(trade_data, aes(x = factor(Year), y = Trade.Value, fill = factor(Commodity.Code))) +
  geom_col(position = position_dodge(width = 0.8)) +
  labs(
    x = "年份",
    y = "交易额(美元)",
    fill = "商品编码",
    title = "各年份不同商品交易额对比"
  ) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()
  • factor(Year)将年份转为分类变量,避免被当作连续数值处理
  • position_dodge(width = 0.8)设置柱子并列显示,宽度可按需调整
  • scale_fill_brewer使用预定义配色,提升分类辨识度

2. 堆叠柱状图(同年份商品交易额堆叠)

适合展示同一年份的总交易额及各商品占比:

ggplot(trade_data, aes(x = factor(Year), y = Trade.Value, fill = factor(Commodity.Code))) +
  geom_col() +
  labs(
    x = "年份",
    y = "交易额(美元)",
    fill = "商品编码",
    title = "各年份不同商品交易额堆叠对比"
  ) +
  scale_fill_brewer(palette = "Set2") +
  theme_minimal()

注:1986年仅存在商品84的数据,绘图时会自动仅显示对应柱子,无需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:38:27