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

使用ggplot筛选2000年后年份绘制年份与codes关联图求助

搞定日期筛选与美观的ggplot可视化方案

没问题,我来帮你解决2000年后数据筛选+好看的柱状图需求,分两步来实现:

1. 先处理数据:筛选+统计计数

首先得确保你的Date列是标准的日期格式(如果原始数据还不是的话,先转换),然后精准筛选2000年及以后的数据,再按日期和Code分组统计数量:

# 先加载需要的包
library(dplyr)
library(ggplot2)

# 把Date列转成日期格式(如果你的原始数据里它是字符串的话)
c$Date <- as.Date(c$Date)

# 筛选2000年后的数据并统计每组的数量
count <- c %>%
  filter(Date >= as.Date("2000-01-01")) %>%  # 只留2000年1月1日之后的数据
  group_by(Date, Code) %>%
  summarise(count = n(), .groups = "drop")  # .groups="drop"可以避免后续绘图的分组残留问题

2. 优化可视化:做出美观的柱状图

接下来我们把统计好的数据绘制成清晰好看的图,比如用颜色区分不同Code,调整坐标轴只显示年份,添加标题标签,优化整体风格:

ggplot(count, aes(x = Date, y = count, fill = Code)) +
  geom_bar(stat = "identity", position = "dodge", alpha = 0.8) +  # 让不同Code的柱子并排,半透明更美观
  scale_x_date(date_breaks = "1 year", date_labels = "%Y") +  # x轴只显示年份,避免密密麻麻的日期
  labs(
    title = "2000年后各Code的数量统计",
    x = "年份",
    y = "数量",
    fill = "Code类型"
  ) +
  theme_minimal() +  # 用简洁的浅色主题
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),  # 标题居中、加粗
    axis.text.x = element_text(angle = 45, hjust = 1),  # x轴年份标签倾斜,防止重叠
    legend.position = "bottom"  # 图例放在底部,更省空间
  )

额外小技巧:按年份聚合统计

如果你的数据是按天记录的,想直接看年度汇总(而不是每天的数量),可以先提取年份再分组统计,这样图表会更简洁:

# 按年份聚合的统计代码
count_yearly <- c %>%
  mutate(Year = format(Date, "%Y") %>% as.integer()) %>%  # 从Date里提取年份
  filter(Year >= 2000) %>%
  group_by(Year, Code) %>%
  summarise(count = n(), .groups = "drop")

# 对应的年度统计绘图代码
ggplot(count_yearly, aes(x = factor(Year), y = count, fill = Code)) +
  geom_bar(stat = "identity", position = "dodge", alpha = 0.8) +
  labs(
    title = "2000年后各Code的年度数量统计",
    x = "年份",
    y = "数量",
    fill = "Code类型"
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.text.x = element_text(angle = 45, hjust = 1),
    legend.position = "bottom"
  )

这样就能得到你想要的、既满足数据筛选又美观的可视化图啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:43:14