在自定义函数中使用ggplot参数会抛出找不到对象错误

时间:2015-11-25 13:44:32

标签: r function ggplot2

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

如果我按以下方式返回我的情节,我的功能正常: (有fill = 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")
    })

但是,我的目标是传递一个参数,为fill参数提供值(=变量),如下面的代码所示。但是这会引发以下错误:

  

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")

我在论坛上看过一些类似的问题,但无法解决我的问题。

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

1 个答案:

答案 0 :(得分:2)

使用'aes_string'代替'aes'解决了我的问题。

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

关于aes&amp;和ggplot2包的aes_string可以在这里找到: What is the difference between aes and aes_string (ggplot2) in R

归功于Axeman&amp;本杰明 - 他们的答案解决了我的问题!