ggplot2循环中的标记图 [英] ggplot2 labeling graphs in a loop

查看:91
本文介绍了ggplot2循环中的标记图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将垂直线和每个图形的垂直线标签放在一个循环中.线的位置保存在数据框网格"中.

I would like to put vertical lines and labels for the vertical lines for each graph in a loop. the position of the line is saved in a dataframe "grid".

尽管该行的位置似乎正确,但标签值却不正确.我的问题是为什么.

Although the position of the line seems correct the label value and its position is off. My question is why.

    library(ggplot2)
    library(grid)
    library(gridExtra)
    
    
    plots <- list()
    
    grid <- data.frame(x=seq(4), y=c(200, 400, 600, 800))
    
    for (i in 1:4) {
      V1 <- rnorm(1000)
      V2 <- seq(1000)
      df <- data.frame(V1, V2)
      
      plots[[i]] <- ggplot(df, aes(x= V2, y=V1)) +
        geom_point() +
      geom_vline(xintercept = grid[i,2], color="red")+ 
      geom_text(aes(x=grid[i,2], label=grid[i,2], y=3))
    
    }
    
    
    grid.arrange(grobs=plots, nrow=2)

推荐答案

理想情况下,应改用annotate.以下代码可以正常工作.

Ideally you should use annotate instead. The following code works as expected.

library(ggplot2)
library(grid)
library(gridExtra)


plots <- list()

grid <- data.frame(x=seq(4), y=c(200, 400, 600, 800))

for (i in 1:4) {
  V1 <- rnorm(1000)
  V2 <- seq(1000)
  df <- data.frame(V1, V2)
  
  plots[[i]] <- ggplot(df, aes(x= V2, y=V1)) +
    geom_point() +
    geom_vline(xintercept = grid[i,2], color="red")+ 
    annotate("text", x=grid[i,2], label=grid[i,2], y=3)
  
}


grid.arrange(grobs=plots, nrow=2)

reprex程序包(v0.3.0)创建于2020-06-26 sup>

Created on 2020-06-26 by the reprex package (v0.3.0)

这篇关于ggplot2循环中的标记图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆