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

R语言绘制双刻度虚拟分面图分组展示异常问题求助

问题原因说明

  • 两次连续使用pivot_longer未保留匹配关系,生成了冗余的笛卡尔积行,数据逻辑错误
  • 绘制折线图时未配置group映射,ggplot无法识别分类x轴下的连线规则,导致折线不显示
  • 两组数据的分组标签没有对应统一,图例无法合并匹配
  • 自定义y轴标签的逻辑依赖渲染顺序,稳定性差,容易出现标签匹配错误的问题

修正后完整代码

# 提前安装依赖包:install.packages(c("tidyverse","ggh4x"))
library(tidyverse)

j <- structure(list(name = c(3, 5, 10, 2), urban_P = c(0.00586510263929619, 
        0.00854700854700855, 0.0104712041884817, 0.0161812297734628), 
            cropland_P = c(0.870967741935484, 0.653846153846154, 0.795811518324607, 
            0.841423948220065), natural_P = c(0.12316715542522, 0.337606837606838, 
            0.193717277486911, 0.142394822006472), U_20y = c(0, 0, 0, 
            0.666666666666667), C_20y = c(0.027681660899654, 0.100719424460432, 
            0.0857142857142857, 0.0116731517509728), N_20y = c(-0.288135593220339, 
            -0.300884955752212, -0.327272727272727, -0.153846153846154
            )), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"
        ))

# 分别处理面积、变化率数据,统一分组标签
area_df <- j %>% 
  select(name, urban_P:natural_P) %>% 
  pivot_longer(cols = -name, names_to = "group", values_to = "num") %>% 
  mutate(
    what = "area_percent",
    group = case_match(
      group,
      "urban_P" ~ "城镇",
      "cropland_P" ~ "耕地",
      "natural_P" ~ "自然植被"
    )
  )

rate_df <- j %>% 
  select(name, U_20y:N_20y) %>% 
  pivot_longer(cols = -name, names_to = "group", values_to = "num") %>% 
  mutate(
    what = "rate_20y",
    group = case_match(
      group,
      "U_20y" ~ "城镇",
      "C_20y" ~ "耕地",
      "N_20y" ~ "自然植被"
    )
  )

dtF <- bind_rows(area_df, rate_df)

# 绘图
ggplot(dtF, aes(x = factor(name), y = num)) +
  facet_grid(what ~ ., scales = "free_y") +
  geom_col(
    data = filter(dtF, what == "area_percent"),
    aes(fill = group)
  ) +
  geom_line(
    data = filter(dtF, what == "rate_20y"),
    aes(color = group, group = group),
    linewidth = 1.2
  ) +
  # 独立配置两个分面的y轴格式
  ggh4x::facetted_pos_scales(
    y = list(
      what == "area_percent" ~ scale_y_continuous(labels = scales::percent_format()),
      what == "rate_20y" ~ scale_y_continuous()
    )
  ) +
  labs(x = "位置", y = NULL, fill = "地类", color = "地类") +
  theme_bw()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:54:04