我想制作一個 ggplot,其 y 軸標簽由預制串列格式化。我發現如果我直接將引數傳遞給ggplotlabels中的函式選項,scale_y_continuous()它作業正常,但如果我通過do.call它傳遞它們會引發錯誤,即使(我認為)這些是等價的。
這是一個例子:
library(scales)
# make the list of arguments
fn_args = list(prefix = "$", big.mark = ",", decimal.mark = ".")
# print an example of a number formatted with these arguments using do.call()
do.call(number, as.list(append(x=10001, fn_args)))
##> [1] "P10,001S"
# print the same number but put the arguments directly in the function
number(10001, prefix = "P", suffix = "S", big.mark = ",", decimal.mark = ".")
##> [1] "P10,001S"
# Great -- they're identical, as expected.
# Now, let's make plots:
library(ggplot2)
# this works and produces a plot with the y-axis formatted nicely
ggplot(mtcars, aes(mpg, cyl))
geom_line()
scale_y_continuous(labels=function(s) number(x = s, prefix = "P", suffix = "S", big.mark = ",", decimal.mark = "."))
# But this one doesn't work:
ggplot(mtcars, aes(mpg, cyl))
geom_line()
scale_y_continuous(labels=function(s) do.call(number, as.list(append(x=s, fn_args))))
##> Error in `f()`:
##> ! Breaks and labels are different lengths
我不明白為什么會出現這個錯誤,因為我認為這兩個公式是相同的。
我會很感激任何人的見解!
謝謝你。
uj5u.com熱心網友回復:
我們需要一個扁平化的list- 在 OP 的代碼中,第append一個引數是x,因此x=s,假設它是為 'x' 引數傳遞的值,而不是命名向量。我們可能需要scale_y_continuous(labels=function(s) do.call(number, append(list(c(x=s)), fn_args)))
library(ggplot2)
ggplot(mtcars, aes(mpg, cyl))
geom_line()
scale_y_continuous(labels=function(s)
do.call(number, c(list(x=s), fn_args)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450751.html
