Beeswarm plot in R: weird gaps?

106 Views Asked by At

I've made a beeswarm plot in R by basically looping through groups in my data and creating a beeswarm for each group and combining into one plot:

#Build color field
color.By.Category <- function(x) {
  if (x == "Polydrug") {
    return("red")
  } else if (x == "Opioid") {
    return("blue")
  } else if (x == "Cocaine") {
    return("green")
  } else if (x == "Gabapentin") {
    return("orange")
  } else if (x == "Meth") {
    return("blue")
  } else if (x == "Benzo") {
      return("pink")
  } else {
    return("black")
  }
}



# Make 5 rows, the first is the legend
par(mfrow=c(5,1), mar=c(0,10,0,0), oma=c(10,0,5,2), bg="black")


# Build legend
drug.categories <- unique(death.data.2$drug)
colr <- sapply(drug.categories, color.By.Category)
xleg <- seq(-10,110, by=23)
beeswarm(xleg, pwcol=colr, 
         horizontal = TRUE, 
         pch=15, 
         method="center", 
         cex=1, 
         xlim=c(-10,110), 
         ylim=c(-10,4))
text(x=xleg+0, y=.5, labels=toupper(drug.categories), col="white", pos=4, cex=1.1)

races <- unique(death.data.2$race)


for (i in 1:length(races)) {

  # Subset to race/ethnicity
  current <- death.data.2[death.data.2$race == races[i],]

  # Draw the symbols
  beeswarm(current$age, pwcol=current$color,
           pch=15, method="center",
           cex=1, horizontal=TRUE,
           ylim=c(-10,10), xlim=c(0,100), axes=FALSE)

  #  label
  mtext(races[i], side = 2, las=1, col="white", cex=.9)
}

x <- seq(0, 100, 5)
axis(side = 1, labels = x, at=x, col="black", col.ticks = "white")
mtext(x, side = 1, outer=FALSE, at=x, line=.8, col="white", cex=.8)
mtext("Age", side=1, at=x[1], outer=FALSE, col="white", line=2, adj=0.05, padj=.5, cex=.8)


# Title
mtext("Overdose Deaths by Substance Type", side=3, outer=TRUE, line=1, cex=1.5, col="white")

Which looks like this:

enter image description here

You can see there are weird gaps (i.e. blank lanes) where no data is showing, which almost looks like some kind of artifact from how the plot is rendering. What's going on here?

1

There are 1 best solutions below

0
On BEST ANSWER

I believe you can remove the gaps by setting breaks = NA in your "Draw the symbols" beeswarm() call. The help file ?beeswarm tells us

breaks Breakpoints (optional). If NULL, breakpoints are chosen automatically. If NA, bins are not used (similar to stripchart with method = "stack").

So when the breaks = NA the binning behavior is prevented and the gaps should not appear.

# Draw the symbols
  beeswarm(current$age, pwcol=current$color,
           pch=15, method="center",
           cex=1, horizontal=TRUE,
           ylim=c(-10,10), xlim=c(0,100), axes=FALSE, breaks = NA)