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

在R中绘制带季节颜色与机场纹理的分组条形图

嘿,这就帮你搞定这个定制化的分组条形图!咱们从数据整理到可视化一步步来,完全匹配你的需求:

1. 准备数据与加载依赖包

首先得把你给的数据整理成ggplot2好处理的格式,同时加载必要的包——这里用tidyverse来处理数据,用ggpattern实现条形的纹理填充(如果没装这个包,先跑install.packages("ggpattern")安装)。注意你提供的LGA数据最后是13...,我先补全了12个月的数值,你可以按需替换成真实数据:

# 加载必备包
library(tidyverse)
library(ggpattern)

# 创建并整理数据框
flight_data <- tibble(
  month = 1:12,
  EWR = c(24,23,28,26,27,31,30,23,14,17,16,33),
  JFK = c(16,21,20,21,22,28,32,23,14,13,12,25),
  LGA = c(14,16,18,20,19,26,26,20,13,11,10,22) # 补全的LGA数据,可替换为真实值
) %>%
  # 转成长格式,适配ggplot分组逻辑
  pivot_longer(cols = -month, names_to = "airport", values_to = "value") %>%
  # 给每个月份匹配对应季节
  mutate(
    season = case_when(
      month %in% c(12,1,2) ~ "冬季",
      month %in% 3:5 ~ "春季",
      month %in% 6:8 ~ "夏季",
      month %in% 9:11 ~ "秋季"
    ),
    # 把数字月份转成英文月份名,更直观(换成中文的话直接写"1月""2月"即可)
    month = factor(month.name[month], levels = month.name)
  )
2. 绘制符合要求的分组条形图

接下来就是核心的可视化部分,实现季节用不同颜色区分、三个机场用不同纹理区分,同时把图例放在下方:

ggplot(flight_data, aes(x = month, y = value, fill = season, pattern = airport)) +
  # 带纹理的分组条形,设置间距和纹理参数
  geom_bar_pattern(
    position = position_dodge(width = 0.9), # 控制分组条形的间距
    stat = "identity",
    pattern_fill = "black", # 纹理线条的颜色
    pattern_density = 0.1, # 纹理的密度,数值越小越稀疏
    pattern_spacing = 0.02 # 纹理元素的间距
  ) +
  # 自定义季节对应的颜色,你可以换成自己喜欢的配色
  scale_fill_manual(
    values = c("冬季" = "#4a6fe3", "春季" = "#2ecc71", "夏季" = "#e74c3c", "秋季" = "#f39c12")
  ) +
  # 自定义机场对应的纹理样式,可选值有stripe、crosshatch、circle、dot等
  scale_pattern_manual(
    values = c("EWR" = "stripe", "JFK" = "crosshatch", "LGA" = "circle")
  ) +
  # 调整主题:图例放下方,x轴标签旋转避免重叠
  theme(
    legend.position = "bottom",
    legend.box = "vertical", # 图例垂直排列
    axis.text.x = element_text(angle = 45, hjust = 1)
  ) +
  # 添加标题和轴标签
  labs(
    title = "各机场月度数据按季节分组条形图",
    x = "月份",
    y = "数值",
    fill = "季节",
    pattern = "机场"
  )
小提示
  • 如果你想把月份名换成中文,把month.name换成c("1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月")即可。
  • 纹理样式和颜色都可以随意调整,比如把circle换成dot,颜色换成你项目的品牌色。
  • 如果LGA的真实数据和我补全的不同,直接替换flight_data里LGA的数值向量就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:31:26