Опираясь на @ конвас-автомат Ответим, начиная с ggplot2.0.x
, вы можете extend ggplot с помощью системы ggproto
и определить свой собственный стат.
Скопировав код ggplot2 stat_boxplot
и сделать несколько изменений, вы можете быстро определить новый стат (stat_boxplot_custom
), который принимает процентили вы хотите использовать в качестве аргумента (qs
) вместо coef
аргумента, что stat_boxplot
использования. Новый стат определяется здесь:
# modified from https://github.com/tidyverse/ggplot2/blob/master/R/stat-boxplot.r
library(ggplot2)
stat_boxplot_custom <- function(mapping = NULL, data = NULL,
geom = "boxplot", position = "dodge",
...,
qs = c(.05, .25, 0.5, 0.75, 0.95),
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = StatBoxplotCustom,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
na.rm = na.rm,
qs = qs,
...
)
)
}
Затем определяется функция слоя. Обратите внимание, что b/c I копируется непосредственно из stat_boxplot
, вам нужно получить доступ к некоторым внутренним функциям ggplot2, используя :::
. Это включает в себя много материала, скопированного непосредственно из StatBoxplot
, но ключевая область заключается в вычислении статистики непосредственно из аргумента qs
: stats <- as.numeric(stats::quantile(data$y, qs))
внутри функции compute_group
.
StatBoxplotCustom <- ggproto("StatBoxplotCustom", Stat,
required_aes = c("x", "y"),
non_missing_aes = "weight",
setup_params = function(data, params) {
params$width <- ggplot2:::"%||%"(
params$width, (resolution(data$x) * 0.75)
)
if (is.double(data$x) && !ggplot2:::has_groups(data) && any(data$x != data$x[1L])) {
warning(
"Continuous x aesthetic -- did you forget aes(group=...)?",
call. = FALSE
)
}
params
},
compute_group = function(data, scales, width = NULL, na.rm = FALSE, qs = c(.05, .25, 0.5, 0.75, 0.95)) {
if (!is.null(data$weight)) {
mod <- quantreg::rq(y ~ 1, weights = weight, data = data, tau = qs)
stats <- as.numeric(stats::coef(mod))
} else {
stats <- as.numeric(stats::quantile(data$y, qs))
}
names(stats) <- c("ymin", "lower", "middle", "upper", "ymax")
iqr <- diff(stats[c(2, 4)])
outliers <- (data$y < stats[1]) | (data$y > stats[5])
if (length(unique(data$x)) > 1)
width <- diff(range(data$x)) * 0.9
df <- as.data.frame(as.list(stats))
df$outliers <- list(data$y[outliers])
if (is.null(data$weight)) {
n <- sum(!is.na(data$y))
} else {
# Sum up weights for non-NA positions of y and weight
n <- sum(data$weight[!is.na(data$y) & !is.na(data$weight)])
}
df$notchupper <- df$middle + 1.58 * iqr/sqrt(n)
df$notchlower <- df$middle - 1.58 * iqr/sqrt(n)
df$x <- if (is.factor(data$x)) data$x[1] else mean(range(data$x))
df$width <- width
df$relvarwidth <- sqrt(n)
df
}
)
Существует также gist here, содержащий этот код.
Затем stat_boxplot_custom
можно назвать так же, как stat_boxplot
:
library(ggplot2)
y <- rnorm(100)
df <- data.frame(x = 1, y = y)
# whiskers extend to 5/95th percentiles by default
ggplot(df, aes(x = x, y = y)) +
stat_boxplot_custom()
# or extend the whiskers to min/max
ggplot(df, aes(x = x, y = y)) +
stat_boxplot_custom(qs = c(0, 0.25, 0.5, 0.75, 1))
kohske, что действительно изменить усов (спасибо!), Но выбросы исчезают. – cswingle
пример был обновлен: есть несколько способов сделать это, но, возможно, это самый простой способ отображать outliers в geom_point. – kohske
Отлично! Функция o должна, вероятно, использовать те же probs = c (0,05, 0,95) [1]/[2], чтобы исключенные точки соответствовали усам. Еще раз спасибо. Похоже, мне нужно узнать больше о stat_summary. – cswingle