如何使用分类x变量沿对角线偏移点?
有没有类似于position_jitter的东西来实现这一点?
ggplot(mpg, aes(cyl, hwy)) + geom_point(position = position_jitter(width = 0.2))在此示例中,每个cyl的最高hwy值应位于该类别的左上角,最低hwy值应位于右下角。
发布于 2018-12-28 07:47:54
这里有一个有点老生常谈的解决方案:
library(tidyverse)
p1 <- ggplot(mpg, aes(cyl, hwy)) + geom_point()
diagonal_plot <- function(.plot) {
p <- ggplot_build(.plot)
p$data[[1]] <-
p$data[[1]] %>%
group_by(x) %>%
mutate(order_y = as.integer(factor(y))) %>%
# making helper column for ranks depending on height of y
ungroup %>%
mutate(x = x - order_y/100) %>%
#this one was just an idea to create the offset to x depending on the rank of y
select(-order_y)
plot(ggplot_gtable(p))
}
diagonal_plot(p1)

由reprex package于2018-12-27创建(v0.2.0)。
https://stackoverflow.com/questions/53950976
复制相似问题