代码之家  ›  专栏  ›  技术社区  ›  Vasily A

如何在绘图的顶部绘制一个网格?

  •  0
  • Vasily A  · 技术社区  · 5 年前

    grob 对象(在我的情况下是 euler ggplot 对象,我想将一个放置在另一个之上,例如:

    library(eulerr)
    library(ggplot2)
    
    df <- data.frame(a=sample(100),b=sample(50:149), c=sample(20:119))
    venn <- euler(list(
      A=df$a,
      B=df$b[1:50],
      C=df$c
    ), shape='ellipse')
    
    p_v <- plot(venn, quantities = T, fills=c('red','green','blue'))
    p_g <- ggplot(df, aes(x=a,y=b)) + geom_point()
    
    # Now I want somehow to draw p_v on top of p_g
    p_g + p_v
    

    应该产生这样的结果: overlayed plot

    我试着用 ggplotify 例如,但找不到摆脱白色矩形的方法,该矩形被绘制为第二个绘图的画布。。。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Allan Cameron    5 年前

    你可以用 annotation_custom :

    p_g + annotation_custom(p_v, xmin  = 0, xmax = 50, ymin = 80, ymax = 150)
    

    enter image description here

    如果要使用对数轴比例,则需要使用 grid p_v 结束 p_g . 首先需要将其放在树丛中,以便指定其位置和尺寸:

    p_g <- ggplot(df, aes(x=a,y=b)) + geom_point() + scale_y_log10()
    
    p_g 
    grid::grid.draw(
      grid::grobTree(p_v$children,
                     vp = grid::viewport(x = unit(0.3, "npc"), 
                                         y = unit(0.7, "npc"), 
                                         width = unit(0.4, "npc"), 
                                         height = unit(0.5, "npc"))))
    

    enter image description here

    如果要将其作为单个R对象,可以执行以下操作:

    obj <- grid::grobTree(ggplotGrob(p_g), grid::grobTree(p_v$children,
                     vp = grid::viewport(x = unit(0.3, "npc"), 
                                         y = unit(0.7, "npc"), 
                                         width = unit(0.4, "npc"), 
                                         height = unit(0.5, "npc"))))
    

    因此 obj 现在是 grob

    另一种方法是使用 geom_grob 从包装 ggpmisc :

    library(ggpmisc)
    
    ggplot(df, aes(x=a,y=b)) + 
      geom_point() + 
      geom_grob(aes(x = 12.5, y = 100, label = list(p_v$children$canvas.grob)),
                vp.width = 0.3, vp.height = 0.4) +
      scale_y_log10()
    

    enter image description here