Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggrepel: plot labels above points

Tags:

r

ggplot2

ggrepel

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 force argument, but then labels don't repel each other when they do overlap.

like image 889
geotheory Avatar asked Oct 28 '25 15:10

geotheory


1 Answers

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 box.padding = unit(-0.5, "lines") gives the labels the points positions (but it probably bases on Capital letters).

iris2$Species <- as.character(iris2$Species)
iris2[7,5] <- "ABCDEFG"

g2 <- ggplot(iris2[1:20,], aes(Sepal.Length, Sepal.Width)) + geom_point(pch = 1, size = 8)
g2 + geom_text_repel(aes(label=Species), segment.color=NA, box.padding = unit(-0.5, "lines"))

enter image description here

like image 117
cuttlefish44 Avatar answered Oct 31 '25 04:10

cuttlefish44



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!