我正在開發一個包,其中包含 ggplot2 函式的包裝器,用于處理由我經常使用的特定程式創建的資料。資料始終具有相同的列名,例如包括“tick”。我想要一個看起來像這樣的函式。
dynamic_plot <-
function(
.data, # A tibble
y_axis, # The name of the variable to put on the y-axis
reporter_names = NULL # The name of the variable to map to color
) {
plt <-
.data |>
ggplot2::ggplot(
mapping = ggplot2::aes(
x = tick,
y = y_axis,
color = reporter_names
)
)
這將允許用戶非常快速地創建一個繪圖,如下所示:
dynamic_plot(
data = my_data,
y_axis = dependent_variable,
reporter_names = independent_variable
)
并快速獲得每個自變數條件一條線的線圖。但是,當我嘗試編譯檔案時,出現錯誤。
Error in FUN(X[[i]], ...) : object 'dependent_variable' not found.
將 'dependent_variable' 添加到 globals.R 并使用 utils::globalVariables() 并沒有幫助。有什么建議嗎?
uj5u.com熱心網友回復:
您可以使用此處描述的“卷曲”方法,參考并傳遞給 ggplot。
dynamic_plot <-
function(.data, # A tibble
y_axis, # The name of the variable to put on the y-axis
reporter_names = NULL # The name of the variable to map to color
) {
plt <-
.data |>
ggplot2::ggplot(
mapping = ggplot2::aes(
x = tick,
y = {{ y_axis }},
color = {{ reporter_names }}
)
)
ggplot2::geom_line()
plt
}
my_data <- tibble::tibble(
tick = rep(1:10, 3),
juiciness = 1:30 * runif(30),
juice = rep(c("a", "b", "c"), each = 10)
)
dynamic_plot(
.data = my_data,
y_axis = juiciness,
reporter_names = juice
)

由reprex 包(v2.0.1)于 2021 年 12 月 29 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397788.html
上一篇:R中的掩碼電話號碼
下一篇:如何根據分組變數填充NA?
