【问题标题】:Plotting of the mean in boxplot before axis log transformation in R在 R 中轴对数转换之前绘制箱线图中的平均值
【发布时间】:2022-08-14 20:36:17
【问题描述】:

我想将平均值包含在箱线图中,但显然,平均值不在它应该在的位置。如果我从数据中计算平均值,则它是 16.2,在对数刻度上等于 1.2。我尝试了各种方法,例如,在转换之前或之后更改 stat_summary 函数的位置,但这不起作用。 非常感谢您的帮助! 你的, 克里斯托夫

代码

数据:

df <- c(2e-05, 0.38, 0.63, 0.98, 0.04, 0.1, 0.16, 0.83, 0.17, 0.09, 0.48, 4.36, 0.83, 0.2, 0.32, 0.44, 0.22, 0.23, 0.89, 0.23, 1.1, 0.62, 5, 340, 47) %>% as.tibble()

输出

df %>%
  ggplot(aes(x = 0, y = value)) +
  geom_boxplot(width = .12, outlier.color = NA) +
  stat_summary(fun=mean, geom=\"point\", shape=21, size=3, color=\"black\", fill=\"grey\") +
  labs(
    x = \"\",
    y = \"Particle counts (P/kg)\"
  ) +
  scale_y_log10(breaks = trans_breaks(\"log10\", function(x) 10^x), labels = trans_format(\"log10\", math_format(10^.x)))
  • 在将数据传递给统计数据之前应用通过比例进行的转换,即您的平均值是10^(mean(log10(df$value))),即.437。这同样适用于箱线图。

标签: r ggplot2 mean boxplot logarithm


【解决方案1】:

stat_summary 计算的平均值是log10(value) 的平均值,而不是value 的平均值。
下面我建议定义一个新函数my_mean 来正确计算平均值。

library(ggplot2)
library(dplyr)
library(tibble)
library(scales)

df <- c(2e-05, 0.38, 0.63, 0.98, 0.04, 0.1, 0.16, 
0.83, 0.17, 0.09, 0.48, 4.36, 0.83, 0.2, 0.32, 0.44, 
0.22, 0.23, 0.89, 0.23, 1.1, 0.62, 5, 340, 47) %>% as.tibble()

# Define the mean function   
my_mean <- function(x) {
   log10(mean(10^x))
}

df %>%
  ggplot(aes(x = 0, y = value)) +
  geom_boxplot(width = .12, outlier.color = NA) +
  stat_summary(fun=my_mean, geom="point", shape=21, size=3, color="black", fill="grey") +
  labs(
    x = "",
    y = "Particle counts (P/kg)"
  ) +
  scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), 
                labels = trans_format("log10", math_format(10^.x)))

【讨论】:

  • 哇!非常感谢 Marco 的快速而有帮助的回复。这节省了一些精力,让我明白了
猜你喜欢
  • 2016-06-27
  • 2011-01-30
  • 2018-06-17
  • 2023-04-03
  • 2017-04-20
  • 1970-01-01
  • 2011-04-19
  • 2019-08-23
  • 1970-01-01
相关资源
最近更新 更多