簡體   English   中英

在 ggplot2::stat_summary() 中使用自定義 function 時出錯

[英]error when using custom function in ggplot2::stat_summary()

我想創建一些箱線圖並在它們上方添加平均值、中位數和 n。 為此,我遵循了某人的代碼。 首先是 function:

box.stats_weight<- function(y, upper_limit = max(mean_weight) * 1.15) {
  return(data.frame(
    y = 0.95 * upper_limit,
    label = paste(
      "n =", length(y), "\n",
      "mean =", round(mean(y), 2), "\n",
      "median =", round(median(y), 2), "\n"
    )
  ))
}

運行該代碼時沒有錯誤。 當我嘗試在我的 Boxplot 中實現它時,會出現錯誤:

Error during wrapup: argument "y" is missing, with no default

我的箱線圖代碼如下所示:

weight_box <- ggboxplot(SB01.data, x = "treatment", y = "mean_weight",
               add = "jitter", shape = "treatment"+
                 stat_summary(fun.data = box.stats_weight(), geom = "text", hjust = 0.5, vjust = 0.9) +
                 theme_classic())

除了評論中已經提到的調用box.stats_weight的問題之外,您的代碼中還有一個與錯誤關閉有關的問題) ,即它應該是ggboxplot(...) +...而你做了ggboxplot(... +...) 此外,由於您沒有提供可重現的示例,我只能猜測mean_weight (用於上限)是您全局環境中的向量。 否則這也會導致錯誤。 在下面的代碼中,我在調用box.stats_weight時直接通過了上限。

使用mtcars作為示例數據:

box.stats_weight <- function(y, upper_limit = max(mean_weight) * 1.15) {
  data.frame(
    y = 0.95 * upper_limit,
    label = paste(
      "n =", length(y), "\n",
      "mean =", round(mean(y), 2), "\n",
      "median =", round(median(y), 2), "\n"
    )
  )
}

library(ggpubr)
#> Loading required package: ggplot2

ggboxplot(mtcars,
  x = "cyl", y = "mpg",
  add = "jitter", shape = "cyl"
) +
  stat_summary(fun.data = ~ box.stats_weight(.x, upper_limit = max(mtcars$mpg) * 1.15), geom = "text", hjust = 0.5, vjust = 0.9) +
  theme_classic()

暫無
暫無

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

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