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

优化geom_text及补全缺失数据的ggplot绘图技术问询

问题1:调整两党得票率文本位置,确保全部显示
  • 核心逻辑:按选区+年份分组,对组内两党得票率降序排序,给高得票率文本向上偏移、低得票率文本向下偏移,避免重叠遮挡。
  • 代码调整示例:
    1. 预处理数据,添加排序标记与位置偏移量:
    library(dplyr)
    library(ggplot2)
    
    # 假设你的数据框名为house_results
    house_results <- house_results %>%
      filter(year == 2022) %>%
      group_by(district) %>%
      # 按得票率降序排序,生成排序标识
      mutate(vote_rank = rank(-vote_pct, ties.method = "first"),
             # 高得票率文本上移0.03,低得票率文本下移0.03
             text_y = vote_pct + ifelse(vote_rank == 1, 0.03, -0.03)) %>%
      ungroup()
    
    1. 调用geom_text时使用调整后的y轴位置:
    ggplot(house_results, aes(x = district, y = vote_pct, fill = party)) +
      geom_col() # 你的柱状图层
      geom_text(aes(y = text_y, label = paste0(round(vote_pct*100), "%")),
                size = 3, color = "white")
    
问题2:补全2022年缺失的选举数据
  • 核心逻辑:按地区+党派分组,提取每组内最近一次(年份最新)的非缺失得票率,替换2022年的缺失值。
  • 代码调整示例:
    library(tidyr)
    
    # 假设包含所有年份数据的原始数据框为all_house_results
    all_house_results <- all_house_results %>%
      group_by(district, party) %>%
      arrange(desc(year)) %>% # 按年份降序排列,优先取最新数据
      # 用本组最近一次有效得票率填充2022年的缺失值
      mutate(vote_pct = ifelse(year == 2022 & is.na(vote_pct), 
                               first(na.omit(vote_pct)), 
                               vote_pct)) %>%
      ungroup()
    
    若存在某地区党派无任何历史数据的情况,可添加默认值(如0),修改代码为:
    mutate(vote_pct = ifelse(year == 2022 & is.na(vote_pct), 
                             coalesce(first(na.omit(vote_pct)), 0), 
                             vote_pct))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:15:05