如何在绘图类型 'h' 中标记超出阈值的值

How to label values beyond threshold in plot type 'h'

使用 mtcars 数据集和带有参数 type= 'h'plot 函数,我只想用 mtcars$wt >4 标记观察结果,但没有成功。我试过了:

 plot(mtcars$wt,type = 'h',ylim = c(0,6))
    abline(h=4)
    text(mtcars$wt,row.names(mtcars[mtcars$wt >4,]),pos =3,col='blue',cex=0.6))

但是所有条形图都被标记为:

我也尝试了 Add labels to plot for specific values in R 提供的解决方案,但未能成功。

如果标签也能以 45 度角位于栏的顶部以避免重叠,那就太好了

可能有多种方法可以解决此问题。我试过这个:

plot(mtcars$wt,type = 'h',ylim = c(0,6))
abline(h=4)
labs <- ifelse(mtcars$wt >4, row.names(mtcars), "")
text(mtcars$wt,labs,pos =3,col='blue',cex=0.6)

对于你的问题的第二部分,我将不得不使用ggplotggrepel,它可能不是你想要的,但它可以避免重叠:

library(ggrepel)
library(tidyverse)
mtcars$x = 1:length(mtcars$wt)
mtcars %>% 
  ggplot(aes(x= x, xend =x, y = 0, yend= wt))+
  geom_segment() +
  geom_text_repel(aes(x= x, y = wt, label = labs), 
                      angle = 45
) 

text 函数参数有特定的顺序(在控制台中输入 ?text),当您不使用参数名称时,函数会按照您指定的顺序填充参数.您似乎忘记定义 y= 左右。

试试这个:

plot(mtcars$wt, type='h', ylim=c(0,6))
abline(h=4)
## here your old call with argument names
# text(x=mtcars$wt, y=row.names(mtcars[mtcars$wt >4,]), pos =3, col='blue', cex=0.6)
text(x=which(mtcars$wt > 4), y=mtcars$wt[mtcars$wt > 4], 
     labels=row.names(mtcars[mtcars$wt > 4,]), pos=3, col='blue', cex=0.6)

但是,这些标签有点混在一起。在这里,我们可以使用 Map 将每个参数一个一个地应用于 text 函数,并且我们可以将调整向量添加到 xy 参数。

plot(mtcars$wt,type='h',ylim=c(0,6))
abline(h=4)
Map(function(x, y, labels) text(x, y, labels, pos=3, col="blue", cex=.6),
    x=which(mtcars$wt > 4) + c(0, -2.8, 0, 2.2),
    y=mtcars$wt[mtcars$wt > 4] + c(0, -.1, .1, -.1),
    labels=row.names(mtcars[mtcars$wt > 4,])
)

当我们有更多标签时,这可能仍然会让读者感到困惑。然后我们可以使用 arrows 在起点 x0, y0 和终点 x1, y1 中定义的位置以及我们使用已有值的位置。

plot(mtcars$wt,type='h',ylim=c(0,8))
abline(h=4)
xpos. <- which(mtcars$wt > 4)
ypos. <- mtcars$wt[mtcars$wt > 4]
Map(function(x, y, labels) text(x, y, labels, pos=3, col="blue", cex=.6),
    x=xpos. + c(0, -6, 0, 6), y=ypos. + c(0, 1, 2, 1), 
    labels=row.names(mtcars[mtcars$wt > 4,])
)
arrows(x0=xpos. + c(0, -6, 0, 6), y0=ypos.+ c(0, 1, 2, 1), x1=xpos., y1=ypos.+.2,
       code=0, col="blue")

要旋转标签,我们可以使用 srt= 选项,例如srt=45 45°。

plot(mtcars$wt,type='h',ylim=c(0,8))
abline(h=4)
text(x=which(mtcars$wt > 4), y=mtcars$wt[mtcars$wt > 4], 
     labels=row.names(mtcars[mtcars$wt > 4,]), pos=3, col='blue', cex=0.6, srt=45)

注意: 最好使用其他设备而不是预览 window,例如 png()pdf(),否则一切都会很烦人时间。请参阅此问题的答案以了解如何执行此操作:

  • How to save a plot as image on the disk?

现在,享受修补的乐趣吧! :)