Home > Net >  Adjust binwidth size for faceted dotplot with free y axis
Adjust binwidth size for faceted dotplot with free y axis

Time:05-27

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")

enter image description here

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)  

enter image description here

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_dotplots which allows to set the binwidth for each facet separately. This however requires some manual work to compute the binwidths 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")

  • Related