r - 仅在某些方面 ggplot 中添加注释(段/箭头)

标签 r ggplot2

这个问题在这里已经有了答案:




8年前关闭。




Possible Duplicate:
Annotating text on individual facet in ggplot2



我正在研究一个包含 3 个物种的数据集。它们是苹果、橙子和香蕉。

我只想在底部面板上注释刻面。但是,默认情况下,我会在所有图上获得注释。我只能在所需的情节上获得文本注释。但是,我很困惑我需要为箭头/段做什么。

这是我的代码:
library(ggplot2)
library(grid)

tempobs <- read.csv("temp data share.csv",header=T, sep=",")
p1 <- ggplot(tempobs,aes(x=time,y=data))+geom_point(data=tempobs,aes(x=time,y=data,colour=group1))+facet_wrap(~id,ncol=1)+theme_bw()
p1 <- p1 + xlab("Julian Day (2008-2009)")+ylab(expression(Temperature~(degree*C)))+ element_blank()+ theme(
    legend.position="right",
    legend.direction="vertical",
    legend.title = element_blank()) +coord_cartesian(xlim=c(250,550))+coord_cartesian(ylim=c(0,40))+scale_x_continuous(breaks=c(250,300,350,400,450,500,550),labels=c("250","300","350","34","84","134","184"))
p1

### This is how it should look like (though shows annotations for all the plots)
p + annotate("text",x=340,y=3,label="2008",size=3)+annotate("segment",x=366,xend=366,y=0,yend=2,size=0.5)+annotate("text",x=390,y=3,label="2009",size=3)+annotate("segment",x=366,xend=310,y=1,yend=1,size=0.5,arrow=arrow(length=unit(0.2,"cm")))+annotate("segment",x=366,xend=420,y=1,yend=1,size=0.5,arrow=arrow(length=unit(0.2,"cm")))


### This is what I did to show text annotation on the bottom panel
ann_text <- data.frame(x=c(340,390),y=c(3,3),id=c("orange"),label=c("2008","2009"))
p1 <- p1 + geom_text(data=ann_text,aes(x=x,y=y,label=label,size=3),show_guide=F)
p1

现在,我想根据整体图添加箭头和线段。

我的数据可以在 https://www.dropbox.com/s/dfcmqrslskwdh80/temp%20data%20share.csv 上找到

我的输出是 enter image description here

这是我只用文本注释得到的。但是对于段注释,我总是出错。您可以注意到底部面板上添加了文本标签 2008 和 2009。

enter image description here

输出显示了我想要的注释,但它是在所有方面。我只想要最底层的。

非常感谢。

问候,
杰巴巴

最佳答案

您还应该为要用于该段的值创建一个数据框(与文本标签相同)。

ann_line<-data.frame(xmid=366,xmin=310,xmax=420,y0=0,y2=2,y=1,
    id=factor("orange",levels=c("apple","banana","orange")))

然后使用 geom_segment()绘制所有元素
p1 + geom_segment(data=ann_line,aes(x=xmid,xend=xmin,y=y,yend=y),arrow=arrow(length=unit(0.2,"cm")),show_guide=F)+
     geom_segment(data=ann_line,aes(x=xmid,xend=xmax,y=y,yend=y),arrow=arrow(length=unit(0.2,"cm")),show_guide=F)+
     geom_segment(data=ann_line,aes(x=xmid,xend=xmid,y=y0,yend=y2),show_guide=F)+   
     geom_text(data=ann_text,aes(x=x,y=y,label=label,size=3),show_guide=F)

enter image description here

关于r - 仅在某些方面 ggplot 中添加注释(段/箭头),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508277/

相关文章:

r - 为什么 data.table 行过滤可以默默地接受函数中缺少的参数而不引发错误?

r - 如何在 R 中匹配多个 ggplot2 图中的调色板?

r - 错误: Found object is not a stat

linux - 使用 R/awk 打印文件中列的标准差

r - 如何改变R中ggplot的高度?

r - 求解 R 中函数的逆

R 读取 HTML 并将其解析为列表

R函数用阴影绘制不等式

r - 函数内 ggplot2 的惰性求值

r - 如何在 ggplot 主题中设置 scale_ defaults?