提问人:Waldi 提问时间:4/7/2021 最后编辑:Waldi 更新时间:7/26/2022 访问量:4314
如何使用 ggrepel 抑制警告
How to suppress warnings with 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
我试过了,但无济于事: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" )
})
答:
0赞
CyG
6/20/2022
#1
您可以通过设置全局警告级别来忽略警告消息,如下所示:
options(warn=-1)
评论
0赞
Waldi
6/20/2022
谢谢你的回答。不确定它是否回答了我的问题:我不想删除延迟警告,而不是所有警告。ggreprel
0赞
CyG
6/20/2022
你一直需要剧情吗?为什么打印绘图后不能只dev.off()?否则我可能会切换到 knitr/rmarkdown 以避免这个问题。
0赞
Waldi
6/21/2022
warn
不幸的是,选项不足以避免所描述的行为。当然,擦除情节可以消除警告问题,但问题是如何避免对这个特定对象发出警告。ggrepel
0赞
Saurav Das
7/26/2022
#2
您可以通过设置最大重叠来执行此操作:
options(ggrepel.max.overlaps = Inf)
评论
0赞
Waldi
7/26/2022
谢谢你的回答。我知道,但我的问题是“我想禁止这些警告,与”的值无关“,因为允许使输出很难在小窗口中阅读。max.overlaps
max.overlaps
Inf
评论
g <- ggplot...; print(suppressWarnings(g))
assign("last.warning", NULL, envir = baseenv())
assign("last.warning", NULL, envir = baseenv())
ggrepel