1
votes

When I run this ggplot2 code using With this dataset (download here)...

ggplot(data=P4L_melt, aes(variable, y=value)) + geom_boxplot(aes(fill=Species), alpha=0.7, lwd=0.5, outlier.shape=NA) + geom_point(position=position_jitterdodge(jitter.width=0),aes(group=Species, colour=Species), alpha=0.5)

I get this plot: enter image description here

It seems to be alright. As you can see, we have three groups (red, green, blue), with the respective observations overlapping the boxplots.

However, if we focus on the bottom left corner, where no red group exists, we see that the blue and green points are misaligned (in DC1, DC2, and DC3). How can I edit the code to solve this?

2
Please add data to question - pogibas
I edited my post with a link to download the dataset @PoGibas - antecessor

2 Answers

1
votes

Ok, here's another try, maybe over the top :)

1) Install latest ggplot2 version:

install.packages('tidyverse')
library('tidyverse')

2) Download my modified version of position-dodge2.r and its dependency position-collide.r from my github

3) Put these files in your working directory for the project and:

source('position-collide.R')
source('position-dodge2.R')

4) Now this code should give you what you want!!

ggplot(data=P4L_melt, aes(variable, y=value)) +
  geom_boxplot(aes(fill=Species), alpha=0.7) +
  geom_point(aes(colour=Species), position=position_dodge2(width=0.75), alpha=0.5)
1
votes

Seems like geom_boxplot and position_jitterdodge treats NA differently...

Here's an (inelegant) workaround:

1) create a column in your df specifying the x-position of the points:

library(ggplot2)
P4L_melt <- read.table('P4L_melt.txt')

P4L_melt$x <- as.numeric(gsub('DC', '', P4L_melt$variable))
P4L_melt$variable <- factor(P4L_melt$variable, levels = paste('DC', unique(P4L_melt$x), sep=''))
P4L_melt$x[P4L_melt$Species=='A'] <- P4L_melt$x[P4L_melt$Species=='A'] - 0.25
P4L_melt$x[P4L_melt$Species=='C'] <- P4L_melt$x[P4L_melt$Species=='C'] + 0.25
P4L_melt$x[P4L_melt$Species=='B'&P4L_melt$variable%in%c('DC1', 'DC2', 'DC3')] <- P4L_melt$x[P4L_melt$Species=='B'&P4L_melt$variable%in%c('DC1', 'DC2', 'DC3')] - 0.2
P4L_melt$x[P4L_melt$Species=='C'&P4L_melt$variable%in%c('DC1', 'DC2', 'DC3')] <- P4L_melt$x[P4L_melt$Species=='C'&P4L_melt$variable%in%c('DC1', 'DC2', 'DC3')] - 0.05

2) use that column as the x-position in geom_point

ggplot(data=P4L_melt, aes(variable, y=value)) + 
  geom_boxplot(aes(fill=Species), alpha=0.7, lwd=0.5, outlier.shape=NA) + 
  geom_point(aes(x=x, group=Species, colour=Species), alpha=0.5) 

result..