How can I offset points along a diagonal line with a categorical x variable?
Is there something similar to position_jitter
to achieve this?
ggplot(mpg, aes(cyl, hwy)) + geom_point(position = position_jitter(width = 0.2))
In this example, the highest hwy
value for each cyl
should be at the top-left of that category and the lowest hwy
value at the bottom-right.
Here's a mildly hacky solution:
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)
Created on 2018-12-27 by the reprex package (v0.2.0).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.