是否可以以编程方式添加ggplot2注释

时间:2018-11-18 17:52:30

标签: r ggplot2

我有以下代码段:

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.3.7/vuetify.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.3.7/vuetify.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<div id="app">
  <v-app>
    <v-layout row>
      <v-select label="height=80" outline height="80" :items="years">
      </v-select>
      <v-select label="height=60" outline height="60" :items="years">
      </v-select>
      <v-select label="height=40" outline height="40" :items="years">
      </v-select>
      <v-select label="height=20" outline height="20" :items="years">
      </v-select>
    </v-layout>
  </v-app>
</div>

如您所见,有21个注释,但是它们的值在第一个循环中进行。有没有办法以编程方式添加注释? for循环或if语句在ggplot中似乎不起作用。如果我有一百个这样的值,那又怎么办却又没有一百行呢?很抱歉,没有reprex,但是代码和目标应该很清楚。

1 个答案:

答案 0 :(得分:1)

您可以将图形另存为字符串,在循环中添加annotate()行,然后执行生成的字符串:

library(ggplot2)


data <- data.frame(x=rnorm(100),y=rnorm(100)) #example data
annotations <- data.frame(x=c(-2,-1,-1),      #annotation information
                          y=c(0,1,2),
                          text=c("An. 1","An. 2", "An. 3"))
p <- "ggplot(data, aes(x,y)) + geom_point()"  #save plot as character string

eval(parse( text=p )) #execute character string


for(i in 1:nrow(annotations)){

  #in each iteration, add one annotate line 
  #with info from the annotations dataframe

  p <- paste(p,paste0('+ annotate("text",',annotations[i,1],',',annotations[i,2],', label ="', annotations[i,3],'", color = "Blue")'))


}

eval(parse( text=p )) #new plot with all annotations