Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

r - How can I access dimensions of labels plotted by `geom_text` in `ggplot2`?

As far as I can see ggplot2 knows the dimensions of labels plotted by geom_text. Otherwise the check_overlap option would not work.

Where are these dimensions stored and how can I access them?


Illustrative example

library(ggplot2)
df <- data.frame(x = c(1, 2), 
                 y = c(1, 1), 
                 label = c("label-one-that-might-overlap-another-label", 
                           "label-two-that-might-overlap-another-label"), 
                 stringsAsFactors = FALSE)

With check_overlap = FALSE (the default), the labels overplot each other.

ggplot(df, aes(x, y)) + 
  geom_text(aes(label = label)) + 
  xlim(0, 3)                              

enter image description here

With check_overlap = TRUE, the second label is not plotted, because ggplot finds an overlap.

ggplot(df, aes(x, y)) + 
  geom_text(aes(label = label), check_overlap = TRUE) + 
  xlim(0, 3)

enter image description here

How does ggplot2 know that those labels overlap? How can I access that information?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are just looking to avoid overlapping labels, the ggrepel package works pretty well.

library(ggplot2)
library(ggrepel)
df <- data.frame(x = c(1, 2), 
                 y = c(1, 1), 
                 label = c("label-one-that-might-overlap-another-label", 
                           "label-two-that-might-overlap-another-label"), 
                 stringsAsFactors = FALSE)
ggplot(df, aes(x, y)) + 
  geom_text_repel(aes(label = label), check_overlap = F) + 
  xlim(0, 3) 

The above code produces the graph below. enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...