Reputation: 393
I was wondering if there is a certain geom or function to make dot/jitter plots where the dots are ordered based on their value. See example below:
Upvotes: 1
Views: 57
Reputation: 173793
A bit late to the party, but the alternative way would be to use facets:
df <- data.frame(x = rep(LETTERS[1:20], 50), y = rnorm(1000))
library(dplyr)
library(ggplot2)
df %>%
group_by(x) %>%
mutate(new_x = seq_along(x),
y = sort(y)) %>%
ggplot(aes(new_x, y)) +
geom_rect(aes(fill = as.factor(as.numeric(as.factor(x)) %% 2)),
xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) +
geom_point(color = "red4", size = 0.5) +
scale_fill_manual(values = c("white", "gray90"), guide = guide_none()) +
facet_grid(.~x, switch = "x") +
theme_classic() +
theme(panel.spacing = unit(0, "points"),
strip.background = element_blank(),
axis.text.x = element_blank(),
axis.ticks.length.x = unit(0, "points"),
strip.placement = "outside")
Upvotes: 2
Reputation: 37923
I don't think there exists one, but we could write a quick and dirty position function that would transform the data in the appropriate way. Example below:
library(tidyverse)
df <- data.frame(
var = LETTERS[sample(1:2, 100, TRUE)],
val = rnorm(100)
)
position_orderdodge <- function(
width = NULL
) {
ggproto(NULL, PositionOrderdodge, width = width)
}
PositionOrderdodge <- ggproto(
"PositionOrderdodge", PositionDodge,
compute_panel = function(data, params, scales) {
data <- flip_data(data, params$flipped_aes)
w <- params$width
data <- data %>% group_by(x, group) %>%
mutate(rank = scales::rescale(rank(y), to = c(-w, w)))
data <- as.data.frame(data)
data$x <- data$x + data$rank
data$rank <- NULL
flip_data(data, params$flipped_aes)
}
)
ggplot(df, aes(var, val)) +
geom_point(position = position_orderdodge(0.2))
Created on 2020-12-07 by the reprex package (v0.3.0)
Note: not tested beyond this example
Upvotes: 5