Search code examples
rplotbeeswarm

R: plot line segment behind points in R


I'm using the 'beeswarm' package and want to plot an abline behind my points. The code below will plot the line on top of my points.

library(beeswarm)
testdf<-data.frame(a=c(1,1,1,2,2,2,3,3,3),b=c(1,2,3,1,4,6,1,3,4))
beeswarm(b ~ a,data=testdf,col="red",bg="red",pch=21)
abline(3,0)

I know this question has been answered for plots just using base R (such as here: How do I draw gridlines using abline() that are behind the data?), but these solutions when applied to my data just create two plots one with an abline and one with the beeswarm plot.

Thanks in advance for your help!


Solution

  • You can just add a second call to beeswarm at the end with the parameter add = TRUE.

    I've made the dots bigger in this example so you can clearly see them plotted over the abline

    library(beeswarm)
    testdf<-data.frame(a=c(1,1,1,2,2,2,3,3,3),b=c(1,2,3,1,4,6,1,3,4))
    beeswarm(b ~ a,data=testdf,col="red",bg="red",pch=21, cex = 5)
    abline(3,0)
    beeswarm(b ~ a,data=testdf,col="red",bg="red",pch=21, cex = 5, add = TRUE)
    

    enter image description here