ggplot geom_point position_jitterdodge not working when color specified?
Asked Answered
I

3

1

I have plotted a boxplot+points. I want to add colors to the points. The position_jitterdodge worked fine without color as shown in Figure B, the points are close, which is I intended to do. But when I try to add colors to the points, the jitter.width parameter doesn't work any more (Figure A). The points are too far apart. I tried different numbers for jitter.width, not working. How do I solve this problem?

library(tidyverse)
library(ggpubr)
mtcars$cyl <- factor(mtcars$cyl)

p1 <- mtcars %>% ggplot(aes(x = cyl, y = mpg, fill = cyl)) +  
  geom_boxplot() +
  geom_point(position = position_jitterdodge(jitter.width = 0.2),
             aes(color = factor(wt)), show.legend = FALSE)

p2 <- mtcars %>% ggplot(aes(x = cyl, y = mpg, fill = cyl)) +  
  geom_boxplot() +
  geom_point(position = position_jitterdodge(jitter.width = 0.2))

ggarrange(p1, p2, labels = c("A", "B"))

ggplot sample

Isaac answered 25/9, 2018 at 20:35 Comment(0)
S
4

In p1, the points are not only jittered, they are also dodged by factor(wt). If you only want jitter, set dodge.width = 0 in position_jitterdodge.

Salute answered 25/9, 2018 at 21:4 Comment(0)
S
2

It looks like the problem is that the points have a discrete color aesthetic, but no group aesthetic. If you want to keep coloring by a discrete variable, add group = cyl to the aesthetics for the geom_point layer. If you're plotting with another dataset, the grouping variable would be the same variable you plot along the x axis.

One catch: you have to increase the jitter.width when you apply grouping for it to be visible. I had to dial it up from 0.2 to 3 here.

Another option would be to color by a continuous variable.

library(tidyverse)
library(ggpubr)

mtcars$cyl=factor(mtcars$cyl)

p3=mtcars %>% ggplot(aes(x=cyl, y=mpg, fill=cyl))+  
  geom_boxplot()+
  geom_point(aes(color = factor(wt), group = cyl),
         position=position_jitterdodge(jitter.width=0.2),
         show.legend = F)

p4=mtcars %>% ggplot(aes(x=cyl, y=mpg, fill=cyl))+  
  geom_boxplot()+
  geom_point(aes(color = wt),
         position=position_jitterdodge(jitter.width=0.2),
         show.legend = F)

ggarrange(p3, p4)

This will render inline eventually, but for now a link: color_and_jitter

Sandor answered 25/9, 2018 at 21:6 Comment(0)
R
1

I do the ggplot(aes(group = cyl)) instead of geom_point(aes(group = cyl)). The geom_point(aes(group = cyl)) doesn't work for me.

Renault answered 2/10, 2023 at 19:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.