ggrepel
可以通过将标签彼此之间的距离推开来避免标签重叠。
该算法取决于视窗大小,当窗口大小改变时会触发回调函数。
如果算法无法避免给定窗口大小的重叠,则会发出警告:
Warning messages:
1: ggrepel: 178 unlabeled data points (too many overlaps). Consider increasing max.overlaps
我希望能够抑制这些警告,无论
max.overlaps
的值如何,因为它们可能会延迟并失去上下文。延迟的原因可能是第一次打印后的回调或更改查看窗口宽度后的回调,如下例所示:
library(ggplot2)
library(ggrepel)
N <- 50
data <- data.frame(x=1:N,y=rep(1,N),label = paste0("Text",1:N))
ggplot(data)+
geom_point(aes(x=x,y=y))+
geom_text_repel(aes(x=x,y=y,label=label),hjust=0, vjust=0, box.padding = 0.5, max.overlaps = 20)
# If the viewing window width is OK, no warning!
# Execute anything in console
1
#[1] 1
# This is OK!
# Now reduce window width with mouse
# No warning yet
# Execute anything in console
1
# Warning messages:
# 1: ggrepel: 41 unlabeled data points (too many overlaps). Consider increasing max.overlaps
# 2: ggrepel: 41 unlabeled data points (too many overlaps). Consider increasing max.overlaps
# 3: ggrepel: 41 unlabeled data points (too many overlaps). Consider increasing max.overlaps
# 4: ggrepel: 47 unlabeled data points (too many overlaps). Consider increasing max.overlaps
# 5: ggrepel: 47 unlabeled data points (too many overlaps). Consider increasing max.overlaps
# 6: ggrepel: 47 unlabeled data points (too many overlaps). Consider increasing max.overlaps
# 7: ggrepel: 47 unlabeled data points (too many overlaps). Consider increasing max.overlaps
# 8: ggrepel: 47 unlabeled data points (too many overlaps). Consider increasing max.overlaps
# 9: ggrepel: 47 unlabeled data points (too many overlaps). Consider increasing max.overlaps
#[1] 1
我尝试了suppressWarnings
和withCallingHandlers
,但都没有用:withCallingHandlers(
suppressWarnings(ggplot(data)+
geom_point(aes(x=x,y=y))+
geom_text_repel(aes(x=x,y=y,label=label),hjust=0, vjust=0, box.padding = 0.5, max.overlaps = 20)
)
, warning=function(w) {
if( any( grepl( "ggrepel", w) ) ) invokeRestart( "muffleWarning" )
})
g <- ggplot...; print(suppressWarnings(g))
不是一个好的选择? - Siriusassign("last.warning", NULL, envir = baseenv())
,它确实可以清除警告,这样我们就可以控制它们何时发生。但是,这并没有禁用它们,当ggrepel
图的窗口大小改变时,需要进行新的刷新。 - WaldiWaldi73
。 - Waldi