各位老师好,我用ggplot2作散点图,命令如下:

ggplot(uu,aes(wz,p))+
  geom_point()+
  geom_hline(yintercept=(-log10(0.01)))+
  theme_classic2()

我想为纵坐标大于2的值添加标注,标注内容为对应的横坐标内容。假如某纵坐标值为3,其横坐标对应点为A1.那么就在点(A1,3)处添加标签为“A1”,请问该怎么写代码。我用geom_text和geom_label试了下,但写的代码不对。由于数据量大,所以不考虑用annotate,望方便的老师帮忙解答一下。谢谢。

效果图如上↑

这个问题我之前也刚好需要到,试过几种姿势来完成任务。点少的话直接用geom_text即可,点多的话可以试试ggrepel包的geom_text_repel函数,代码:

library(ggplot2)
library(dplyr)
library(ggrepel)

## example data
uu <- data.frame(wz=rnorm(50,2),p=runif(50))


gg <- ggplot(uu,aes(wz,p))+
  geom_point()+
  geom_point(data=uu %>% filter(wz >2),color="red")+
  geom_hline(yintercept=(-log10(0.01)))+
  theme_classic()+
## annotate points
  geom_text_repel(data=uu %>% filter(wz >2),aes(label=sprintf("%0.2f", round(wz, digits = 2))))

print(gg)

    tctcab 非常感谢,我用笨方法:

    i=ggplot(uu,aes(wz,-log10(p)))+geom_point()+geom_hline(yintercept=(-log10(0.01)))+theme_classic2()
    i=i+theme(axis.text.x = element_blank())+theme(axis.ticks = element_blank())
    ui=subset(uu,p<0.01)
    i+geom_text_repel(data=ui,aes(x=wz,y=-log10(p),label=wz)) 

    您的代码更灵活,非常感谢!

    刚刚看了 Hadley 的《R for Data Science》就看到这个帖子。二楼的解法和书中的例子做法一样。楼主可以去看看那本书,我觉得不错。