代码之家  ›  专栏  ›  技术社区  ›  maycca

ggplot2:在绘图区域外绘制几何图形线段()

  •  2
  • maycca  · 技术社区  · 7 年前

    我在ggplot2中创建了两个方面的图。我想在绘图区域外添加一个箭头。多个问题试图解决这个问题: How to draw lines outside of plot area in ggplot2? Displaying text below the plot generated by ggplot2

    但我不能让我的榜样起作用。另外,我希望有一个更简单的方法来实现这一点?

    我试图增加 plot.margins coord_cartesian() ,但都没用。

    enter image description here

    enter image description here

    # read library to assess free data
    library(reshape2)
    library(ggplot2)
    
    
    ggplot(tips,
           aes(x=total_bill,
               y=tip/total_bill)) + 
      geom_point(shape=1) +
      facet_grid(. ~ sex) +
      # define the segment outside the plot
      geom_segment(aes(x = 10, 
                       y = -0.25, 
                       xend = 10, 
                       yend = 0),
                   col = "red",
                   arrow = arrow(length = unit(0.3, "cm"))) +
      theme_bw() +
      # limit the displayed plot extent
      coord_cartesian(ylim = c(0, 0.75)) +
      # increase plot margins - does not help
      theme(plot.margin = unit(c(1,1,1,0), "lines"))
    
    2 回复  |  直到 7 年前
        1
  •  8
  •   user20650    7 年前

    clip="off" 在里面 coord_cartesian . 我也使用 expand scale_y 从零开始y轴。上面有一点手动选择 y 开始位置。

    所以你的例子

    library(reshape2)
    library(ggplot2)
    
    ggplot(tips,
           aes(x=total_bill,
               y=tip/total_bill)) + 
      geom_point(shape=1) +
      facet_grid(. ~ sex) +
      annotate("segment", x=12, y=-0.05, xend=12, yend=0,
                   col="red", arrow=arrow(length=unit(0.3, "cm"))) +
      scale_y_continuous(expand=c(0,0))+
      theme_bw() +
      coord_cartesian(ylim = c(0, 0.75), clip="off") +
      theme(plot.margin = unit(c(1,1,1,0), "lines"))
    

    (我变了 geom_segment annotate 因为你没有映射美学)

    产生

    enter image description here

        2
  •  3
  •   tjebo    7 年前

    这是一个解决办法,这不是完全超令人满意的,因为你将需要发挥周围的位置,你的阴谋。它主要使用自定义注释,可以使用 cowplot

    library(ggplot2) 
    library(cowplot)
    library(reshape2)
    

    首先用相同的坐标限制定义绘图。

    p <- 
      ggplot(tips, aes(x = total_bill, y = tip/total_bill)) + 
      geom_point(shape = 1) +
      facet_grid(. ~ sex) +
      theme_bw() +
      coord_cartesian(ylim = c(0, 0.75), xlim = c(0, 50)) 
    
    arrow_p <- 
      ggplot(tips) +
      geom_segment(aes(x = 1, y = -1, xend = 1, yend = 0),
                   col = "red",
                   arrow = arrow(length = unit(0.3, "cm"))) +
      coord_cartesian(ylim = c(0, 0.75), xlim = c(0,50)) +
      theme_void()
    

    arrow_p 在空白背景上创建,用作覆盖。现在,您可以使用以下工具将其定位到所需位置:

     ggdraw() +
        draw_plot(p) +
        draw_plot(arrow_p, x = 0.10, y = 0.05) +
        draw_plot(arrow_p, x = 0.57, y = 0.05)
    

    enter image description here

    不幸的是,你必须在这里反复试验。也可以更改或指定的宽度/高度/比例参数 draw_plot() 也许有更好的方法,但这是一个相当直接的解决方法。。。

    推荐文章