Я нахожусь на ранних стадиях изучения, как продлить ggplot2
.Я хотел бы создать пользовательский geom
и связанный stat
.Моей отправной точкой была виньетка .Кроме того, я извлек выгоду из этого и этого .Я пытаюсь собрать шаблон, чтобы научить себя и, надеюсь, других.
Основной вопрос:
Внутри моей функции calculate_shadows()
необходимый параметр params$anchor
равен NULL
.Как я могу получить к нему доступ?
Цель, описанная ниже, предназначена исключительно для изучения того, как создавать пользовательские функции stat
и geom
, это не реальная цель: как вы можете видеть на скриншотахЯ знаю, как использовать возможности ggplot2
для построения графиков.
geom
прочитает данные и для предоставленных переменных ("x", "y")
построит график (если не найдется лучшего слова) shadows
: горизонтальная линия min(x)--max(x)
напо умолчанию y=0
и вертикальная линия min(y)--max(y)
по умолчанию x=0
.Если опция указана, эти «якоря» могут быть изменены, например, если пользователь поставит x = 35, y = 1
, горизонтальная линия будет проведена в точке пересечения y = 1
, а вертикальная линия будет нарисована в точке пересечения x = 35
.Использование:
library(ggplot2)
ggplot(data = mtcars, aes(x = mpg, y = wt)) +
geom_point() +
geom_shadows(x = 35, y = 1)
stat
прочитает данные и для предоставленных переменных ("x", "y")
вычислит shadows
в соответствии со значением stat
.Например, передавая stat = "identity"
, тени будут вычисляться для минимального и максимального значений данных (как это делается с помощью geom_shadows
).Но, пройдя stat = "quartile"
, тени будут вычислены для первого и третьего квартиля.В более общем смысле можно передать такую функцию, как stats::quantile
с аргументами args = list(probs = c(0.10, 0.90), type = 6)
, для вычисления теней, используя 10-й и 90-й процентили и метод квантиля типа 6. Использование:
ggplot(data = mtcars, aes(x = mpg, y = wt)) +
geom_point() +
stat_shadows(stat = "quartile")
К сожалению, мое незнакомое с расширением ggplot2
остановило меня далеко от цели.Эти сюжеты были «подделаны» с geom_segment
.На основании приведенного выше руководства и обсуждений и проверки существующего кода, например stat-qq
или stat-smooth
, я собрал базовую архитектуру для этой цели.Он должен содержать много ошибок, я был бы благодарен за руководство.Также обратите внимание, что подойдет любой из этих подходов: geom_shadows(anchor = c(35, 1))
или geom_shadows(x = 35, y = 1)
.
Теперь вот мои усилия.Сначала geom-shadows.r
, чтобы определить geom_shadows()
.Во-вторых, stat-shadows.r
для определения stat_shadows()
.Код не работает как есть.Но если я выполню его содержимое, оно выдаст желаемую статистику.Для ясности я удалил большую часть вычислений в stat_shadows()
, например квартили, чтобы сосредоточиться на основных моментах.Есть очевидная ошибка в макете?
geom-shadows.r
#' documentation ought to be here
geom_shadows <- function(
mapping = NULL,
data = NULL,
stat = "shadows",
position = "identity",
...,
anchor = list(x = 0, y = 0),
shadows = list("x", "y"),
type = NULL,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomShadows,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
anchor = anchor,
shadows = shadows,
type = type,
na.rm = na.rm,
...
)
)
}
GeomShadows <- ggproto("GeomShadows", Geom,
# set up the data, e.g. remove missing data
setup_data = function(data, params) {
data
},
# set up the parameters, e.g. supply warnings for incorrect input
setup_params = function(data, params) {
params
},
draw_group = function(data, panel_params, coord, anchor, shadows, type) {
# draw_group uses stats returned by compute_group
# set common aesthetics
geom_aes <- list(
alpha = data$alpha,
colour = data$color,
size = data$size,
linetype = data$linetype,
fill = alpha(data$fill, data$alpha),
group = data$group
)
# merge aesthetics with data calculated in setup_data
geom_stats <- new_data_frame(c(list(
x = c(data$x.xmin, data$y.xmin),
xend = c(data$x.xmax, data$y.xmax),
y = c(data$x.ymin, data$y.ymin),
yend = c(data$x.ymax, data$y.ymax),
alpha = c(data$alpha, data$alpha)
), geom_aes
), n = 2)
# turn the stats data into a GeomPath
geom_grob <- GeomSegment$draw_panel(unique(geom_stats),
panel_params, coord)
# pass the GeomPath to grobTree
ggname("geom_shadows", grobTree(geom_grob))
},
# set legend box styles
draw_key = draw_key_path,
# set default aesthetics
default_aes = aes(
colour = "blue",
fill = "red",
size = 1,
linetype = 1,
alpha = 1
)
)
stat-shadows.r
#' documentation ought to be here
stat_shadows <-
function(mapping = NULL,
data = NULL,
geom = "shadows",
position = "identity",
...,
# do I need to add the geom_shadows arguments here?
anchor = list(x = 0, y = 0),
shadows = list("x", "y"),
type = NULL,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
stat = StatShadows,
data = data,
mapping = mapping,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
# geom_shadows argument repeated here?
anchor = anchor,
shadows = shadows,
type = type,
na.rm = na.rm,
...
)
)
}
StatShadows <-
ggproto("StatShadows", Stat,
# do I need to repeat required_aes?
required_aes = c("x", "y"),
# set up the data, e.g. remove missing data
setup_data = function(data, params) {
data
},
# set up parameters, e.g. unpack from list
setup_params = function(data, params) {
params
},
# calculate shadows: returns data_frame with colnames: xmin, xmax, ymin, ymax
compute_group = function(data, scales, anchor = list(x = 0, y = 0), shadows = list("x", "y"), type = NULL, na.rm = TRUE) {
.compute_shadows(data = data, anchor = anchor, shadows = shadows, type = type)
}
)
# Calculate the shadows for each type / shadows / anchor
.compute_shadows <- function(data, anchor, shadows, type) {
# Deleted all type-checking, etc. for MWE
# Only 'type = c(double, double)' accepted, e.g. type = c(0, 1)
qs <- type
# compute shadows along the x-axis
if (any(shadows == "x")) {
shadows.x <- c(
xmin = as.numeric(stats::quantile(data[, "x"], qs[[1]])),
xmax = as.numeric(stats::quantile(data[, "x"], qs[[2]])),
ymin = anchor[["y"]],
ymax = anchor[["y"]])
}
# compute shadows along the y-axis
if (any(shadows == "y")) {
shadows.y <- c(
xmin = anchor[["x"]],
xmax = anchor[["x"]],
ymin = as.numeric(stats::quantile(data[, "y"], qs[[1]])),
ymax = as.numeric(stats::quantile(data[, "y"], qs[[2]])))
}
# store shadows in one data_frame
stats <- new_data_frame(c(x = shadows.x, y = shadows.y))
# return the statistics
stats
}
.