2017-10-08 30 views
0

我正在嘗試編寫一個函數,該函數會創建繪圖並且遇到一個我不明白的錯誤。這是一個簡單的例子。如何編寫一個函數,將NULL傳遞給ggplot而不會出現美觀錯誤

重複的例子:

library (ggplot2) 
# Sample data 
xdata = 0:20 
ydata = 20:40 
dat <- data.frame(xdata, ydata) 

# This works 
line_p <- ggplot(dat, aes(x = xdata, y = ydata, group = NULL, color = NULL)) + geom_line() 
line_p 

我希望下面的工作,但得到一個美觀的錯誤,但在這種情況下,變量x和y的長度相同。這些問題似乎對於組和顏色具有NULL的默認值。我試圖顯式傳遞NULL,以及aes_group和aes_color作爲函數變量,但這也不起作用。

# Using a function doesn't work: 

# create function 
line_function <- function(mydata  = dat, 
          xinput  = x, 
          yinput  = y, 
          aes_group = NULL, 
          aes_color = NULL, 
          ...) { 

    lineplot <- ggplot(dat, aes(x = xinput, y = yinput, group = aes_group, color = aes_color)) + geom_line() 
} 


# test the function 
line_test_p <- line_function(
    mydata = dat, 
    xinput = xdata, 
    yinput = ydata 
) 

line_test_p 

測試有明確的投入

# test the function again with explicit NULL inputs 

line_test2_p <- line_function(
    mydata = dat, 
    xinput = xdata, 
    yinput = ydata, 
    aes_group = NULL, 
    aes_color = NULL 
) 

line_test2_p 

是沒可能寫一個通用的函數,其中ggplot將解釋NULL值的,如果沒有一個功能起作用的例子,還是我失去了別的東西?

謝謝!

回答

0

總之,你應該檢查出aes_string以編程方式創建審美映射。它允許您使用變量存儲字符串的名稱創建審美映射。這樣,將列名作爲參數傳遞給函數並創建相應的圖很容易。

你的函數以下版本的工作對我來說:

# create function 
line_function <- function(mydata  = dat, 
          xinput  = "x", # note the defaults are 
          yinput  = "y", # strings here 
          aes_group = NULL, 
          aes_color = NULL, 
          ...) { 

    ggplot(mydata, # this should be the argument, not the global variable dat 
     # now we create the aes binding with aes_string 
     aes_string(x = xinput, 
        y = yinput, 
        group = aes_group, 
        color = aes_color)) + 
    geom_line() 
} 

現在你可以使用函數來創建你的例子:

# test the function 
line_test_p <- line_function(
    mydata = dat, 
    xinput = "xdata", # note the strings 
    yinput = "ydata" 
) 

# test the function again with explicit NULL inputs 
line_test2_p <- line_function(mydata = dat, 
           xinput = "xdata", # and strings here 
           yinput = "ydata", 
           aes_group = NULL, 
           aes_color = NULL) 

,事情應該制定出適合您。同樣,請檢查documentation,因爲您可以通過不同的方式來完成此操作,並且您可能會因不同的目的或偏好而採用不同的方式。

+0

安德魯,就是這樣,謝謝。閱讀文檔後,最簡單的改變是將線圖線改爲:** lineplot < - ggplot(mydata,aes_(x = xinput,y = yinput,group = aes_group,color = aes_color))+ geom_line()** I也應該使用** mydata **作爲你提到的函數中的變量,而不是** dat ** – DaveM

相關問題