【问题标题】:Using ggplot parameters in a custom function throws object not found error在自定义函数中使用 ggplot 参数会引发找不到对象错误
【发布时间】:2015-11-25 13:44:32
【问题描述】:

我编写了一个函数来加载空间数据,从输入数据集中提取数据并将该数据集与空间数据合并。然后我的函数返回一个地图,我的案例被绘制在该地图上。

如果我按以下方式返回我的绘图,我的函数可以正常工作: (填充 = totalCases)

    return ({
      ggplot() +
      geom_polygon(data = sl_adm2_Month, aes(x = long, y = lat, group = group,
                                           fill = totalCases), colour = "white") +
      geom_text(data = sl_adm2_months_names_DF, aes(label = NAME_2, x = long.1, y = lat.2, group = NAME_2), size = 3) + 
#       labs(title = paste("Ebola", str_sub(as.character(variable), 6, -1), "cases by district in Sierra Leone - until",  format(as.Date(date), "%B %Y"))) + 
      xlab("") + 
      ylab("") + 
      theme_gray() + 
      theme(legend.position = "bottom")
    })

但是,我的目标是传递一个参数,为填充参数提供值(= 变量),正如您在下面的代码中看到的那样。但这会引发以下错误:

eval(expr, envir, enclos) 中的错误:找不到对象“变量”

这是我的代码:

  plotMonths <- function(data, variable, date) {
    # Reloading district polygons
    sl_adm2_months <- readOGR("C:/Users/woba/Documents/Ordina/TFS-Projects/Ordina - Mail Analytics/Johnson/Wouter/03. GeoData map - R/Sierra Leone adm2", "SLE_adm2", verbose = TRUE, stringsAsFactors = FALSE)
    sl_adm2_months_DF <- fortify(sl_adm2_months, region = "NAME_2") 

    # Getting the correct District names
    colnames(sl_adm2_months_DF)[7] <- "District"
    sl_adm2_months_DF$District <- ifelse(sl_adm2_months_DF$District == "Western Rural", "Western Area Rural", as.character(sl_adm2_months_DF$District))
    sl_adm2_months_DF$District <- ifelse(sl_adm2_months_DF$District == "Western Urban", "Western Area Urban", as.character(sl_adm2_months_DF$District))
    sl_adm2_months_DF$District <- as.factor(sl_adm2_months_DF$District)

    #Extracting district names for plotting
    sl_adm2_months_names_DF <- data.frame(long = coordinates(sl_adm2_months[, 1]), lat = coordinates(sl_adm2_months[, 2]))
    sl_adm2_months_names_DF[, "ID_2"] <- sl_adm2_months@data[, "ID_2"]
    sl_adm2_months_names_DF[, "NAME_2"] <- sl_adm2_months@data[, "NAME_2"]

    # Subset May data
    sl_Month <- data[data$Country == "Sierra Leone" & data$Date <= as.Date(date), ]
    sl_Month <- droplevels(sl_Month)
    sl_Month[is.na(sl_Month)] <- 0
    confirmed <- ddply(sl_Month, .(Localite), function(x){max(x$cmlConfirmed.cases, na.rm = T)})
    cases <- ddply(sl_Month, .(Localite), function(x){max(x$cmlCases, na.rm = T)})
    deaths <- ddply(sl_Month, .(Localite), function(x){max(x$cmlDeaths, na.rm = T)})
    sl_Month <- merge(cases, deaths, by = "Localite")
    sl_Month <- merge(sl_Month, confirmed, by = "Localite")
    sl_Month <- droplevels(sl_Month)
    sl_Month <- droplevels(sl_Month)
    colnames(sl_Month)<- c("District", "totalCases", "totalDeaths", "totalConfirmed")
    sl_Month <- sl_Month[-which(sl_Month$District == "National"),]  

    # Merging Month data with District polygons 
    sl_adm2_Month <- merge(sl_adm2_months_DF, sl_Month, by = "District", all.x = TRUE)
    sl_adm2_Month$totalCases <- as.numeric(sl_adm2_Month$totalCases)
    sl_adm2_Month$totalDeaths <- as.numeric(sl_adm2_Month$totalDeaths)
    sl_adm2_Month$totalConfirmed <- as.numeric(sl_adm2_Month$totalConfirmed)

    #NA to 0 for values missing for districts
    sl_adm2_Month[is.na(sl_adm2_Month)] <- 0

    #Sorting
    sl_adm2_Month <- sl_adm2_Month[order(sl_adm2_Month$District, sl_adm2_Month$order), ]

    # Prints & Views
    print(head(sl_Month))
    View(sl_Month)
    View(sl_adm2_Month)

    Sys.setlocale("LC_TIME", "English")

   # Plotting Cases
    return ({
      ggplot() +
      geom_polygon(data = sl_adm2_Month, aes(x = long, y = lat, group = group,
                                           fill = variable), colour = "white") +
      geom_text(data = sl_adm2_months_names_DF, aes(label = NAME_2, x = long.1, y = lat.2, group = NAME_2), size = 3) + 
#       labs(title = paste("Ebola", str_sub(as.character(variable), 6, -1), "cases by district in Sierra Leone - until",  format(as.Date(date), "%B %Y"))) + 
      xlab("") + 
      ylab("") + 
      theme_gray() + 
      theme(legend.position = "bottom")
    })
  }

  # Plotting the months - variable = second input and must be IN c(totalDeaths, totalCases, totalConfirmed)
  plotMonths(final_dataset, "totalCases", "2014-05-31")

我在论坛上阅读了一些类似的问题,但无法解决我的问题。

非常欢迎任何有关如何解决此问题的帮助!

【问题讨论】:

  • variable 似乎不是您的数据框中的一列。您应该以某种方式将variable 添加到sl_adm2_Month,这应该可以解决您的错误。
  • 哦,如果variable 是一个字符串,表示用于fill 的列,那么您应该查看aes_string
  • 是的,你可能想要aes_string(x = "long", y = "lat", group = "group", fill = variable) 或类似的。
  • 非常感谢大家,aes_string 似乎工作得很好!我过去一直在使用 aes 并且从来没有遇到过我必须使用 aes_string 的情况......只是查看了 aes 和 aes_string 之间的区别,现在我很清楚为什么我需要使用这个。 :)
  • 感谢@Axeman 提供的信息,用正确的答案更新了这个主题。

标签: r function ggplot2


【解决方案1】:

使用 'aes_string' 而不是 'aes' 解决了我的问题。

aes_string(x = "long", y = "lat", group = "group", fill = variable)        

关于 ggplot2 包的 aes 和 aes_string 之间的差异的解释可以在这里找到: What is the difference between aes and aes_string (ggplot2) in R

所有功劳归功于 Axeman 和 Benjamin - 他们的回答解决了我的问题!

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多