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

如何在R中将按季度分类的dataframe绘制为多类别直方图

实现方案

你需要的是按季度分组的分类柱状图(你提到的「直方图」通常用于展示单个连续变量的数值分布,你的需求是不同季度下三类观测值的计数对比,属于分组/堆叠柱状图场景),以下提供两种可直接运行的实现方案:

方案1:基础R绘图实现

# 加载处理yearqtr格式依赖包
library(zoo)

# 提取三类观测值转为矩阵,行对应类别,列对应季度
cat_matrix <- t(as.matrix(df23[, c("Categorie1", "Categorie2", "Categorie3")]))

# 绘制并排柱状图,将beside参数改为FALSE可生成堆叠柱状图
bar_pos <- barplot(cat_matrix,
                   beside = TRUE,
                   col = c("red", "blue", "green"),
                   width = 0.25,
                   xlab = "季度",
                   ylab = "出现次数",
                   axes = FALSE)

# 自定义X轴标签为标准季度格式
axis(1, at = colMeans(bar_pos), labels = as.yearqtr(df23$date), las = 2)
axis(2)

# 添加图例
legend("topleft",
       legend = c("类别1", "类别2", "类别3"),
       fill = c("red", "blue", "green"),
       bty = "n")

方案2:ggplot2实现(更灵活美观)

library(ggplot2)
library(tidyr)
library(zoo)

# 宽表转长表,适配ggplot2的分组映射逻辑
df_long <- pivot_longer(df23,
                        cols = starts_with("Categorie"),
                        names_to = "观测类别",
                        values_to = "出现次数")

# 绘图
ggplot(df_long, aes(x = as.factor(date), y = 出现次数, fill = 观测类别)) +
  # position_dodge对应并排柱状图,改为position_stack()可生成堆叠柱状图
  geom_col(position = position_dodge(0.9), width = 0.8) +
  # 格式化X轴为季度显示
  scale_x_discrete(labels = function(x) as.yearqtr(as.numeric(x))) +
  labs(x = "季度", y = "出现次数") +
  # 自定义和你原有散点图一致的配色
  scale_fill_manual(values = c("Categorie1" = "red", "Categorie2" = "blue", "Categorie3" = "green")) +
  theme_bw() +
  # X轴标签倾斜避免重叠
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:57:05