R: plot line segment behind points in R

526 Views Asked by At

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!

2

There are 2 best solutions below

1
On BEST ANSWER

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

0
On

Pass the abline call to panel.first within the beeswarm function



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, panel.first = abline(3,0))

Created on 2020-05-14 by the reprex package (v0.3.0)