ggplot2 自定义 grob 不会扩展到绘图之外

问题描述

我正在尝试使用 annotate_custom 在我的绘图之外创建线条以将我的轴分成多个部分。我知道 this post 提出了类似的问题,但出于某种原因,使用负值作为线的最小值不会将线延伸到图之外。

示例代码

library(ggplot2)
library(grid)

data("iris")
ggplot(iris,aes(x=Species,y=Petal.Width)) +
  geom_bar(stat='identity')+coord_flip()+
  annotation_custom(grob = linesGrob(),xmin = 2.5,xmax = 2.5,ymin = -90,ymax = 0)+
  annotation_custom(grob = linesGrob(),xmin = 1.5,xmax = 1.5,ymax = 0)

我得到了什么:

enter image description here

我想要的:

enter image description here

解决方法

默认情况下,设置不允许任何图形元素剪裁到绘图区域之外。您可以通过任何 coord_* 函数(例如 coord_cartesian()coord_fixed()...)关闭剪辑,因此在您的情况下,请使用 coord_flip(clip="off") 以允许 grobs 扩展情节中的任何地方:

ggplot(iris,aes(x=Species,y=Petal.Width)) +
  geom_bar(stat='identity')+coord_flip(clip='off')+
  annotation_custom(grob = linesGrob(),xmin = 2.5,xmax = 2.5,ymin = -90,ymax = 0)+
  annotation_custom(grob = linesGrob(),xmin = 1.5,xmax = 1.5,ymax = 0)

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...