使用y轴刻度之间的距离作为ggplot2中的变量

时间:2016-05-22 23:05:23

标签: r ggplot2 axis

有没有办法将y轴上的刻度线之间的距离用作ggplot函数中的变量?

我想绘制一个注释,其y坐标可以“响应”图形的y轴刻度。

在下面的例子中,我希望var1是从特定图的参数中获取的连续y轴刻度之间的距离,而不是用户定义的常量。

数据:

EXse2<- data.frame(wk=c(1,2), EX=c(4.457143, 2.580952), se=c(0.4209481,0.5519333))

代码:

var1<- 0.1
labEX<- "\u002A\u002A"
library(ggplot2)
ggplot(EXse2, aes(x=factor(wk), y=EX, group=1))+
  geom_errorbar(aes(ymin=EX-se, ymax=EX+se), width=.2, size=1)+
  geom_line(size=1)+
  geom_point(size=2)+
  annotate("text", label=labEX, x=1.5, y=(mean(EXse2$EX[1:2])+var1))+
  xlab("period")+
  ylab(expression(bar(EX)))+
  theme(
        panel.background=element_blank(),
        panel.border = element_blank(), 
        panel.grid.minor.x=element_blank(),
        panel.grid.major.x=element_blank(),
        panel.grid.minor.y = element_line(colour = "#d9d9d9"), 
        panel.grid.major.y = element_line(colour = "#bfbfbf"),  
        axis.line = element_line()
        )

1 个答案:

答案 0 :(得分:0)

您可以通过先创建绘图,使用ggplot_build提取刻度距离然后添加注释来实现此目的:

library(ggplot2)

EXse2<- data.frame(wk=c(1,2), EX=c(4.457143, 2.580952), se=c(0.4209481,0.5519333))
labEX<- "\u002A\u002A"

#first, put your plot in p1
p1 <-
ggplot(EXse2, aes(x=factor(wk), y=EX, group=1))+
  geom_errorbar(aes(ymin=EX-se, ymax=EX+se), width=.2, size=1)+
  geom_line(size=1)+
  geom_point(size=2)+
  # I HAVE REMOVED THE ANNOTATE HERE
  xlab("period")+
  ylab(expression(bar(EX)))+
  theme(
    panel.background=element_blank(),
    panel.border = element_blank(), 
    panel.grid.minor.x=element_blank(),
    panel.grid.major.x=element_blank(),
    panel.grid.minor.y = element_line(colour = "#d9d9d9"), 
    panel.grid.major.y = element_line(colour = "#bfbfbf"),  
    axis.line = element_line()
  )

# extract axis limits
yminticks <- ggplot_build(p1)$panel$ranges[[1]]$y.minor_source
# subtract first tick from second
var1 <- yminticks[2] - yminticks[1]

# and now add the annotate and plot
p1 + 
  annotate("text", label=labEX, x=1.5, y=(mean(EXse2$EX[1:2])+var1))