gpt4 book ai didi

r - ggplot2 中自定义几何的自定义比例

转载 作者:行者123 更新时间:2023-12-04 02:28:42 24 4
gpt4 key购买 nike

我正在为 ggplot2 构建自定义 geom。请参阅下面的代码。但是,我试图默认实现 scale_y_reverse() 。我应该在代码中的何处以及如何添加它?我找不到任何关于此的信息。

geomName <- ggplot2::ggproto("geomName", ggplot2::Geom,

required_aes = c("x", "y"),
default_aes = ggplot2::aes(colour = "black", fill = "orange", alpha = 1, linetype = 1),
draw_key = ggplot2::draw_key_polygon,

draw_group = function(data, panel_scales, coord) {
coords <- coord$transform(data, panel_scales)
grid::polygonGrob(
coords$x, coords$y,
gp = grid::gpar(col = coords$colour, group = coords$Id, fill = coords$fill, lty = coords$linetype)
)
}
)

geom_Name <- function(mapping = NULL, data = NULL, position = "identity",
stat = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {

ggplot2::layer(
geom = geomName, mapping = mapping, data = data, stat = stat,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}

谢谢你的帮助

最佳答案

好吧,它的名称是“ggplot”,它是基于图形语法的,它反过来推论几何、比例、刻面、主题等应该完全分开。这使得很难从 geom 的上下文中设置比例。

通常,比例是根据 scale_type.my_class() S3 方法选择的,但这发生在 geoms 实际上首先在 ggproto 的 setup_data() 中看到数据之前方法。这可以防止 geom ggproto 快速将 y 重新分类为虚拟类以引发 scale_y_reverse(),我试过了。

也就是说,我们可以只记下 geom_sf() 是如何处理的,并在我们使用 geom 时自动添加一个 scale_y_reverse()(比如 geom_sf() 添加了 coord_sf())。通过将 geom-part 和 scale-part 包装在一个列表中,它们会按顺序添加到绘图中。我能想到的唯一缺点是,只要覆盖比例,用户就会收到警告。

library(ggplot2)

geomName <- ggplot2::ggproto(
"geomName", ggplot2::Geom,

required_aes = c("x", "y"),
default_aes = ggplot2::aes(colour = "black", fill = "orange", alpha = 1, linetype = 1),
draw_key = ggplot2::draw_key_polygon,

draw_group = function(data, panel_scales, coord) {
coords <- coord$transform(data, panel_scales)
grid::polygonGrob(
coords$x, coords$y,
gp = grid::gpar(col = coords$colour, group = coords$Id, fill = coords$fill, lty = coords$linetype)
)
}
)

geom_Name <- function(mapping = NULL, data = NULL, position = "identity",
stat = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {

list(ggplot2::layer(
geom = geomName, mapping = mapping, data = data, stat = stat,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
), scale_y_reverse())
}

df <- data.frame(x = rnorm(10), y = rnorm(10))

ggplot(df, aes(x, y)) +
geom_Name()

reprex package 创建于 2021-01-06 (v0.3.0)

编辑评论中的问题:

是的,您可以设置一个默认组。问题是,您可以确定默认的无组解释会将 group 设置为 -1,但您不能确定用户没有指定 >aes(..., 组 = -1)。如果您愿意接受这一点,那么您可以将以下 setup_data ggproto 方法添加到 geomName 对象:

geomName <- ggplot2::ggproto(
"geomName", ggplot2::Geom,
...
setup_data = function(data, params) {
if (all(data$group == -1)) {
data$group <- seq_len(nrow(data))
}
data
},
...
)

然后代替seq_len(nrow(data)),你可以输入任何你希望的默认分组。

关于r - ggplot2 中自定义几何的自定义比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65597760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com