I would like to adjust the binwidth
of a faceted geom_dotplot
while keeping the dot sizes the same.
Using the default binwidth
(1/30 of the data range), I get the following plot:
library(ggplot2)
df = data.frame(
t = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2),
x = 1,
y = c(1, 2, 3, 4, 5, 100, 200, 300, 400, 500)
)
ggplot(df, aes(x=x, y=y))
geom_dotplot(binaxis="y", stackdir="center")
facet_wrap(~t, scales="free_y")
However, if I change the binwidth
value, the new value is taken as an absolute value (and not the ratio of the data range), so the two facets get differently sized dots:
geom_dotplot(binaxis="y", stackdir="center", binwidth=2)
Is there a way to adjust binwidth
so it is relative to its facet's data range?
CodePudding user response:
One option to achieve your desired result would be via multiple geom_dotplot
s which allows to set the binwidth for each facet separately. This however requires some manual work to compute the binwidth
s so that the dots are the same size for each facet:
library(ggplot2)
y_ranges <- tapply(df$y, factor(df$t), function(x) diff(range(x)))
binwidth1 <- 2
scale2 <- binwidth1 / (y_ranges[[1]] / 30)
binwidth2 <- scale2 * y_ranges[[2]] / 30
ggplot(df, aes(x=x, y=y))
geom_dotplot(data = ~subset(.x, t == 1), binaxis="y", stackdir="center", binwidth = binwidth1)
geom_dotplot(data = ~subset(.x, t == 2), binaxis="y", stackdir="center", binwidth = binwidth2)
facet_wrap(~t, scales="free_y")