簡體   English   中英

ggplot2 的圖層附加運算符

[英]Layer appending operator for ggplot2

我喜歡ggplot2 ,但我不想每次添加圖層時都寫myplot <- myplot + 例如,

# Load library
library(ggplot2)

# Create plot
myplot <- ggplot(iris) 
myplot <- myplot + geom_point(aes(Sepal.Length, Sepal.Width))
myplot <- myplot + ggtitle("This is a plot")
myplot <- myplot + theme_dark()
myplot

因此,我想創建類似於 C 中的加法復合賦值運算符 ( += ) 的東西。

# Operator for appending layer
`%+=%` <- function(g, l){
  eval.parent(substitute(g <- g + l))
}

# Test appending function
myplot2 <- ggplot(iris) 
myplot2 %+=% geom_point(aes(Sepal.Length, Sepal.Width))
myplot2 %+=% ggtitle("This is a plot")
myplot2 %+=% theme_dark()
myplot2

reprex 包(v0.3.0) 於 2019 年 12 月 20 日創建

如您所見,它給出了與普通語法相同的結果。 這種方法改編自此處針對不同問題給出的解決方案,並附有警告; 但是,我不清楚為什么這可能有問題。

我的問題是:定義上述運算符的潛在有害或意外副作用是什么? 有沒有更好的方法來達到同樣的結果?

老實說,唯一的缺點是您的構造函數不如 ggplot 的靈活。 ggplot 已經有一個重載的運算符+ ,它不能直觀地與您的函數一起使用。 以此為例:

gg <- ggplot(iris)
gg %+=% geom_point(aes(Sepal.Length, Sepal.Width)) + theme_dark() #plots similar to your answer
   # only geom_point was added to gg variable
   #in other words the expression above is doing this
gg <- ggplot(iris)
gg <- gg + geom_point(aes(Sepal.Length, Sepal.Width))
gg + theme_dark()

這是中綴函數始終從左到右求值的結果。 因此,除非您能夠捕獲表達式的其余部分,否則將您的函數與 ggplot 的+一起使用的希望不大

在當前狀態下,您一次只能分配第一層,這可能比執行效率/整潔要低

gg <- gg + geom_point(aes(Sepal.Length,Sepal.Width)) +
    ggtitle("This is a plot") +
    theme_dark()

它本身也無法使用,但是如果您將其重新編碼為:

`%+=%` <- function(g, l) {
  UseMethod("%+=%")
}

`%+=%.gg` <- function(g, l){
  gg.name <- deparse(substitute(g))
  gg.name <- strsplit(gg.name, split = "%+=%", fixed= T)[[1]][1]
  gg.name <- gsub(pattern = " ", replacement = "", x = gg.name)
  gg <- g +l
  assign(x = gg.name, value = gg, envir = parent.frame())
}

gg <- ggplot(iris)
gg %+=% geom_point(aes(Sepal.Length, Sepal.Width)) %+=% theme_dark() #will now save left to right

我真的只是挑剔,但如果您的意圖是通過一次添加一個圖層來使用它,那么無論如何您的原始功能似乎都可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM