繁体   English   中英

ggplot2:在绘图区域外绘制geom_segment()

[英]ggplot2: Draw geom_segment() outside of the plot area

我在ggplot2中创建了两个facet图。 我想在情节区域外添加一个箭头。 多个问题试图解决这个问题: 如何在ggplot2中的绘图区域之外绘制线条? 在ggplot2生成的图表下方显示文本

但我不能让我的榜样有效。 另外,我希望有一种更简单的方法来实现这一目标吗?

我试图增加plot.margins并使用coord_cartesian() ,但都没有帮助。

在此输入图像描述

相反,我想:

在此输入图像描述

我的假例子:

# 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"))

您可以使用coord_cartesian的参数clip="off"在面板外部绘制。 我还使用scale_yexpand参数将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因为你没有映射美学)

哪个产生

在此输入图像描述

这是一种不太令人满意的解决方法,因为您需要玩弄地块的位置。 它主要使用自定义注释,可以使用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()

在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)

在此输入图像描述

不幸的是,你必须在这里试错。 您还可以更改指定draw_plot()的宽度/高度/比例参数。 可能有更好的方法,但这是一个相当直接的解决方法......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM