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

8
我已经用ggplot2创建了两个多面板图。我想在图形区域外添加一个箭头。有多个问题试图解决这个问题: 如何在ggplot2中绘制图形区域外的线条? 在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个回答

11

您可以在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

这会产生以下结果:

enter image description here


1
感谢您的回答@user20650!请问您能否在其中包含一个结果图吗?这样每个人都可以在不需要重新运行R环境中的代码的情况下查看结果图。 - maycca
coord_cartesian正在将一些绘制的点移动到图形区域之外。 - Herman Toothrot
你是说@HermanToothrot;如果点刚好在轴边界上,在使用“clip”后,有些点会在绘图面板外面吗? - user20650
图的上部分点被截掉了,我不得不设置ylim = c(0, 1)。我只是在暗示你的解决方案可能不适用于所有图。 - Herman Toothrot
嗨@HermanToothrot; 啊,明白了。好的,是的,这些限制是特定于绘图的。 - user20650

3

这是一种解决方法,不是非常令人满意,因为您需要调整图表的位置。主要使用自定义注释,可以使用 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)

这里输入图片描述

很遗憾,在这里你需要尝试和错误。你也可以更改draw_plot()的宽度/高度/比例参数。可能有更好的方法,但这是一个相当简单的解决方法...


谢谢你的回答,这是非常有趣的方法! - maycca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接