Vertical equivalent of position_dodge for geom_point on categorical scale
I would transform y_factor
to numeric and use continuous y-axis. Trick is to add to "noise" y numeric values by n group.
df_with_overlap <- df_with_overlap %>%
# Transform y factors to numbers
mutate(y_num = as.numeric(y_factor)) %>%
# Add scaling factor by n group
mutate(y_num = y_num + case_when(n == 1 ~ 0,
n == 2 ~ -0.1,
n == 3 ~ 0.1))
# Plot y numeric values
ggplot(df_with_overlap, aes(x, y_num, color = n)) +
geom_point() +
# On y-axis put original labels and no one will notice that it's actually a continuous scale
scale_y_continuous(breaks = 1:5,
labels = levels(df_with_overlap$y_factor)) +
labs(y = "y_factor")
Thanks to @aosmith for suggesting ggstance::position_dodgev()
. It's exactly what I was looking for. I increased the oversampling so the effect is more obvious.
df <- expand.grid(
y_factor = paste0('factor_',1:5),
x =1:100
)%>%as.tbl
seed<-1
df_with_overlap<-df%>%
sample_frac(1.5,replace = TRUE)%>%
group_by(y_factor,x)%>%
mutate(n=factor(1:n()))
ggplot(data=df_with_overlap, aes(x=x, y=y_factor, col=n))+
geom_point(position=ggstance::position_dodgev(height=0.3))