geotheory - 1 month ago 31
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,

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

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.

library(dplyr)
## 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)

[EDITED]
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)

Source (Stackoverflow)