问题
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"))
回答1:
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
.
回答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
来源:https://stackoverflow.com/questions/52506296/ggplot-geom-point-position-jitterdodge-not-working-when-color-specified