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

R管道链中ggplot使用case_when自定义标签提示Var1未找到错误

问题排查与解决方案

错误原因

  • 核心问题是动态关联Var1列的colour参数放在了geom_text的aes()映射之外:只有全局固定的美学参数可以放在aes()外,凡是需要调用数据框列、按行取值的动态规则,都必须放在aes()内部,否则ggplot无法在数据环境中找到Var1对象。你之前尝试给Var1加.$前缀也无法解决问题,本质是参数位置错误,管道传递的数据集只会在aes()内部的环境中自动关联行数据。
  • 附加问题:你提供的示例数据生成代码存在语法错误,rep的参数位置多了右括号,无法正常生成带有效计数字段的数据集。

修复后完整可运行代码

# 提前加载依赖包
library(tidyverse)

# 修正后的数据生成代码
padmin1<- data.frame(q0005_0001 = rep(c("Insuficiente1", "Poco Suficiente2","Regular3","Suficiente4","Muy Suficiente5"),5))

# 修正后的绘图代码
padmin1 %>% 
  rename(Var1=q0005_0001) %>% 
  ggplot(aes(x = "", y = 1, fill = fct_rev(ordered(Var1)))) +  
  geom_bar(stat = "identity", width = 0.2) +
  # 将colour规则移入aes映射内
  geom_text(aes(label = after_stat(count), 
                colour = case_when(
                  Var1 == "Insuficiente1" ~ "white",
                  Var1 == "Poco Suficiente2" ~ "black",
                  Var1 == "Regular3" ~ "black",
                  Var1 == "Suficiente4" ~ "white",
                  Var1 == "Muy Suficiente5" ~ "white",
                  TRUE ~ "white"
                )), 
            position = position_stack(vjust=0.5), 
            fontface = "bold") +
  # 新增颜色规则:直接使用case_when返回的颜色值,不额外生成颜色图例
  scale_color_identity(guide = "none") +
  coord_flip() +
  labs(title= "La información brindada por la facultad le resultó...", caption = "Elaborado por SS, 2021") + 
  # 原主题配置保持不变
  theme(axis.title = element_blank(), 
        line = element_blank(),
        panel.background = element_rect(fill = "transparent", color = NA),
        plot.background = element_rect(fill = "transparent", color = NA),
        legend.position = "bottom", 
        panel.border = element_blank(), 
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.background = element_rect(fill = "transparent", linetype = "solid", colour = "transparent"),
        legend.box.background = element_rect(fill = "transparent", colour = "transparent"),
        axis.text = element_blank()) +
  scale_fill_manual("Leyenda", values = c("Insuficiente1"="#8A0000", "Poco Suficiente2"="#FFCD2F", "Regular3"="#DAA600", "Suficiente4"="#144D6C", "Muy Suficiente5"="#071C27")) 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 21:21:03