首页 > 解决方案 > 如何使用 ggrepel 抑制警告

问题描述

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

在此处输入图像描述

我试过suppressWarningswithCallingHandlers无济于事:

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" )
})

标签: rggplot2callbackwarnings

解决方案


推荐阅读