问题描述
据我所知ggplot2
知道 geom_text
绘制的标签尺寸.否则check_overlap
选项将不起作用.
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?
说明性例子
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
(默认设置)时,标签会相互重叠.
With check_overlap = FALSE
(the default), the labels overplot each other.
ggplot(df, aes(x, y)) +
geom_text(aes(label = label)) +
xlim(0, 3)
对于check_overlap = TRUE
,不会绘制第二个标签,因为ggplot
发现重叠.
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)
ggplot2
如何知道这些标签重叠?我如何访问该信息?
How does ggplot2
know that those labels overlap? How can I access that information?
推荐答案
如果您只是想避免标签重叠,则ggrepel软件包的效果很好.
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.
这篇关于如何在ggplot2中访问由geo_text绘制的标签的尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!