Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create vertically non-overlapping labels next to boxplot using ggplot2

If want to create a boxplot with overlaid points which are labeled at the right hand side. I tried geom_dl form the directlabels package, but get stuck.

library(ggplot2)
library(directlabels)

set.seed(0)
x <- data.frame(label=LETTERS[1:15], 
                x="a",
                y = rnorm(15))
x$xpos <- as.numeric(x$x) + .25

g <- ggplot(x, aes(x=x, y=y)) + 
  geom_boxplot(width=.4) +
  geom_point(col="blue")

Position labels without overlap control using method last.points.

g + geom_dl(aes(x=xpos, label=label), method = "last.points") 

enter image description here

Using method last.qp to avoid overlaps fails.

g + geom_dl(aes(x=xpos, label=label), method = "last.qp")   # fails

Error in approx(df[, x.var], df[, tiebreak.var], xvals) : 
  need at least two non-NA values to interpolate

Any ideas, how to get geom_dl running or achieve proper placemant in another way?

Add-on

Using method last.bumpup as @lukeA suggested below works quite fine. However, some labels are still overlapping. Is there a way to tweak this?

enter image description here

Add-on 2

I think the problem only arises when using a factor with more than one level on x.

set.seed(0)
x <- data.frame(label=LETTERS[1:24], 
                g1 = c("a"),
                g2 = c("a", "b"),
                y = rnorm(24))
x$g1 <- as.factor(x$g1)
x$g2 <- as.factor(x$g2)
x$xpos1 <- as.numeric(x$g1) + .25
x$xpos2 <- as.numeric(x$g2) + .25

The label placement for the first plot is fine. For the second with two levels the overlaps remain.

# one group
ggplot(x, aes(x=g1, y=y)) + 
  geom_boxplot(width=.4) +
  geom_point(col="blue") +
  geom_dl(aes(x=xpos1, label=label), method= "last.bumpup")

enter image description here

Two levels

# two groups
ggplot(x, aes(x=g2, y=y)) + 
  geom_boxplot(width=.4) +
  geom_point(col="blue") +
  geom_dl(aes(x=xpos2, label=label), method= "last.bumpup")

enter image description here

like image 270
Mark Heckmann Avatar asked Jan 21 '26 06:01

Mark Heckmann


1 Answers

You could use the last.bumpup method, which combines last.points and bumpup (last.bumup <- list("last.points","bumpup")):

g + geom_dl(aes(x=xpos, label=label), method = "last.bumpup")  

enter image description here

like image 60
lukeA Avatar answered Jan 23 '26 21:01

lukeA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!