如何使用ggplot2完整显示“ Inf”标签?

问题描述 投票:0回答:2

当我使用ggplot2包绘制具有无穷大值的线时,即使我使用了较大的“ nudge_y”参数,也无法完全显示其标签。手动文本可以得到结果,但这不是我的答案。如何完整显示?

x=seq(1,3,1)
y=c(1/3,Inf,3/3)
dt=data.frame(x=x,y=y,z=round(y,2))
ggplot(dt)+geom_line(aes(x=x,y=y))+
     geom_text(aes(x=x,y=y,label=z))

img

r ggplot2 label infinite
2个回答
1
投票

您可以添加+ coord_cartesian(clip = "off")以显示被剪裁超出绘图区域的部分。

enter image description here


0
投票

使用ggrepel包也可以实现您的目标。

library(tidyverse)
library(ggrepel)

x = seq(1,3,1)
y = c(1/3,Inf,3/3)
dt = data.frame(x=x,y=y,z=round(y,2))

ggplot(dt, aes(x=x,y=y)) +
 geom_line()+
 geom_label_repel(aes(label=z), nudge_x = .05)

enter image description here

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.