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

如何在R中创建带分组次Y轴的柱状图?数据及代码问题求助

绘制目标柱状图的修正方案

你的现有代码存在几个核心问题:

  • 数据是宽格式,ggplot需要长格式才能按Type(In-situ/Remote sensing)分组绘制并列柱
  • 代码里的pH.value是不存在的变量,y轴字段也选错了
  • 分面设置错误,目标图是按Satellite分面,而非Satellite+Reference

下面是完整的修正步骤:

1. 把数据转成ggplot适配的长格式

ggplot对长格式数据支持更好,我们用tidyr包把宽格式转成长格式:

library(tidyverse)

# 构造你的数据框(如果是从文件读取,替换成read.table/read_csv即可)
d1 <- tibble(
  Satellite = c("Landsat 8 OLI", "Landsat 8 OLI", "Landsat 5 TM", "MODIS", "MODIS", "MODIS", "Sentinel2A MSI"),
  Reference = c("Zhu et al., 2022", "Huang et al., 2021", "Huang et al., 2021", "Wu et al., 2022", "Yu et al., 2016", "Xu et al., 2010", "Huang et al., 2023"),
  `In-situ` = c(0.624, 2.15, 2.15, 0.778, 0.0895, 0.1305, 0.31),
  `Remote sensing` = c(0.554325, 1.52, 2.3, 0.64, 0.10546, 0.11799, 0.41)
)

# 转换为长格式
d1_long <- d1 %>%
  pivot_longer(
    cols = c(`In-situ`, `Remote sensing`),
    names_to = "Type",
    values_to = "Value"
  )

2. 修正后的绘图代码

按照目标图的样式调整参数,确保分面、柱子分组都符合预期:

ggplot(d1_long, aes(x = Reference, y = Value, fill = Type)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  facet_wrap(vars(Satellite), strip.position = "left") +
  theme_minimal() +
  theme(
    strip.placement = "outside",
    axis.text.x = element_text(angle = 45, hjust = 1),
    panel.spacing = unit(1, "lines")
  ) +
  labs(x = "参考文献", y = "数值", fill = "数据类型") # 可选:替换成你需要的标签文字

关键调整说明

  • position_dodge(width = 0.8):让同个参考文献下的两个柱子并列不重叠
  • strip.position = "left":把卫星名称的分面标签放在左侧,和目标图一致
  • 旋转x轴标签:避免参考文献名称过长导致重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:32:54