geotheory geotheory - 1 year ago 166
R Question

ggrepel: plot labels above points

I want to plot labels precisely above points where possible (no overlap), but ggrepel seems to insist on plotting slightly above or below. E.g.

require(ggplot); require(ggrepel)

ggplot(iris[1:10,], aes(Sepal.Length, Sepal.Width)) +
geom_point(pch=1, size=8) +
geom_text_repel(aes(label=Species), segment.color=NA,
point.padding=unit(0, "lines"))

enter image description here

You can of course reduce the
argument, but then labels don't repel each other when they do overlap.

Answer Source

As far as I can see, you can avoid overlapping by giving point.padding the same value as geom_point(size). And you can define above position by giving nudge_y a very small plus value.

 ## an example data (delete duplicated data)
iris2 <- iris %>% distinct(Sepal.Length, Sepal.Width, .keep_all = T)

g <- ggplot(iris2[1:20,], aes(Sepal.Length, Sepal.Width)) + geom_point(pch=1, size=8)
g + geom_text_repel(aes(label=Species), segment.color=NA, 
                    point.padding = unit(8, "points"), nudge_y = 1.0E-6)

I guess the point.padding value, - point.size + 0.5, gives the labels the points positions (but it probably bases on Capital letters).

iris2$Species <- as.character(iris2$Species)
iris2[7,5] <- "ABCDEFG"
a <- 8    # point size

g2 <- ggplot(iris2[1:20,], aes(Sepal.Length, Sepal.Width)) + geom_point(pch = 1, size = a)
g2 + geom_text_repel(aes(label=Species), segment.color=NA, 
                     point.padding = unit(-a + 0.5, "points"), nudge_y = 1.0E-6)

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download