I'm looking to add point data so that is sits adjacent to a box in a boxplot. When I run the below example, the point data does not separate for each fill factor. Is there a way to add point data that corresponds to the box when plotting 2 factors in a boxplot? Can this also be added so it is to the left of the box rather than on top of it?
Group<-c("A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B")
Value<-c(2,1,6,4,2,5,3,6,8,1,10,2,2,3,4,6)
Round<-c("Round 1","Round 1","Round 1","Round 1","Round 2","Round 2","Round 2","Round 2",
"Round 1","Round 1","Round 1","Round 1","Round 2","Round 2","Round 2","Round 2")
data<-as.data.frame(cbind(Group,Value,Round))
data$Round<-as.factor(data$Round)
data$Group<-as.factor(data$Group)
data$Value<-as.numeric(data$Value)
str(data)
ggplot(data,aes(Group,Value,fill=Round))
geom_point(aes(colour=Round))
geom_boxplot(width=0.5,position = position_dodge(width=0.7))
labs(fill= "Round",x="Group",y="Value")
CodePudding user response:
You can use position_dodge
for the points like this:
ggplot(data,aes(Group,Value,fill=Round))
geom_point(aes(colour=Round), position = position_dodge(width = 0.9))
geom_boxplot(width=0.5,position = position_dodge(width=0.7))
labs(fill= "Round",x="Group",y="Value")
Output:
You can change the width
to change the position of the points.
Another option is using position_jitterdodge()
:
ggplot(data,aes(Group,Value,fill=Round))
geom_point(aes(colour=Round), position = position_jitterdodge())
geom_boxplot(width=0.5,position = position_dodge(width=0.7))
labs(fill= "Round",x="Group",y="Value")
Output:
CodePudding user response:
As Quinten says, one would normally use position_dodge
here. However, you can't do this if you want the points to sit just to the left of the boxes, since you would need to nudge and dodge at the same time, which isn't currently an option. Instead, you can nudge the groups in two layers:
ggplot(data,aes(Group, Value, fill = Round))
Map(\(r, d) geom_point(aes(colour = Round), subset(data, Round == r),
position = position_nudge(x=d)), r = levels(data$Round), d = c(-0.33,0.02))
geom_boxplot(width = 0.5, position = position_dodge(width = 0.7))