How can I access dimensions of labels plotted by `

2020-06-03 09:02发布

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?

标签: r ggplot2
1条回答
虎瘦雄心在
2楼-- · 2020-06-03 09:46

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

查看更多
登录 后发表回答