这是一个使用 GeomPolygon 进行水平交叉的非常粗略的统计数据。这只是为了演示一种非常简单直接的方法来实现这一点。这不是一个很好的统计数据,因为
- 合适的比例取决于比例(基本上需要设置coord_equal),
- 您需要对组非常具体
但这可能是一个好的开始......
library(tidyverse)
StatCross <- ggproto("StatCross", Stat,
compute_group = function(data, scales, width = .1, params) {
x <- data$x
y <- data$y
new_x <- c(rep(x + width, 2),
rep(x + 4 * width, 2),
rep(x + width, 2),
rep(x - width, 2),
rep(x - 4 * width, 2),
rep(x - width, 2))
new_y <- c(y + 4* width,
rep(y + width, 2),
rep(y - width, 2),
rep(y - 4*width, 2),
rep(y - width, 2),
rep(y + width, 2),
y + 4*width)
cross_data <- data.frame(x = new_x, y = new_y)
cross_data
},
required_aes = c("x", "y")
)
stat_cross <- function(mapping = NULL, data = NULL, geom = "polygon",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, width = 0.1, ...) {
layer(
stat = StatCross, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, width = width, ...)
)
}
iris %>%
mutate(index = row_number()) %>%
ggplot(aes(Sepal.Length, Sepal.Width, group = index)) +
stat_cross(width = .01, fill = "yellow", color = "black")
由reprex package (v1.0.0) 于 2021-03-15 创建