如何在ggplot2中访问由geo_text绘制的标签的尺寸?

时间:2019-04-15 10:11:51

标签: r ggplot2

据我所知ggplot2 知道geom_text绘制的标签的尺寸。否则,check_overlap选项将不起作用。

这些尺寸存储在哪里,如何访问它们?


说明性例子

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)

使用check_overlap = FALSE(默认设置),标签会相互重叠。

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

enter image description here

使用check_overlap = TRUE时,第二个标签未绘制,因为ggplot发现重叠。

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

enter image description here

ggplot2如何知道这些标签重叠?我如何访问该信息?

1 个答案:

答案 0 :(得分:-1)

如果您只是想避免标签重叠,则ggrepel软件包的效果很好。

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) 

上面的代码产生下图。 enter image description here