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

R语言ggplot2局部定义自定义key_glyph函数无法识别如何解决

问题原因

当你给key_glyph参数传入字符串"cust"时,ggplot2默认只会在全局环境中查找名称为draw_key_cust的函数,不会检索foo()函数的内部环境,因此会出现函数无法识别的问题。

解决方法

不需要将自定义key glyph函数放到全局环境,只需要把key_glyph的参数从字符串"cust"改为直接传入你内部定义的函数对象draw_key_cust即可。

修正后的完整代码
library(tidyverse)
library(lubridate)

set.seed(123)

y <- rnorm(100)

df <- tibble(y) %>% 
  mutate(os = factor(rep_len(1:5, 100)),
         date = seq(from = ymd('2013-01-01'), by = 1, length.out = 100))

foo <- function() {

  draw_key_cust <- function(data, params, size) {
    if (data$colour %in% c("red", "blue"))
      draw_key_vpath(data, params, size)
    else
      draw_key_path(data, params, size)
  }
  
  ggplot(df, aes(x = date, y = y, colour = os)) +
    geom_line() +
    geom_vline(
      aes(xintercept = min(date), linetype = 'os 1'), 
      colour = 'red', key_glyph = draw_key_cust) +
    geom_vline(
      aes(xintercept = median(date), linetype = 'os 2'), 
      colour = 'black', key_glyph = draw_key_cust) +
    geom_hline(
      aes(yintercept = 1, linetype = "dashed"), 
      colour = "blue", key_glyph = draw_key_cust
    ) +
    geom_hline(
      aes(yintercept = -1, linetype = "dashed 2"), 
      colour = "purple", key_glyph = draw_key_cust
    ) +
    
    scale_linetype_manual(
      name = 'lines',
      values = c(2, 2, 1, 1),
      guide = guide_legend(override.aes = list(colour = c('red', 'black', 'blue', "purple"))))

}

foo()
运行效果

运行效果图

内容的提问来源于stack exchange,提问作者Bear Bile Farming is Torture

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:27:03