首页 > 解决方案 > 如何防止ggplot剪切超出范围的点

问题描述

我正在使用以下代码尝试保留超出绘图区域范围的几何元素,但它似乎仍然将它们剪裁到绘图区域上方一定距离之外。

g <- ggplot(iris, aes(x = Species, y = Petal.Length)) +
  stat_summary(geom = 'bar', fun.y = mean) +
  geom_point() +
  scale_y_continuous(limits = c(0,8), expand = c(0,0), oob = function(x, ...) x) +
  geom_text(label = 'obText', aes(x = 2, y = 9)) #+ 
  # theme(plot.margin = unit(c(60,5.5,5.5,5.5), "points"),
  #       aspect.ratio = 1)

gb <- suppressWarnings(ggplot_build(g))
gt <- ggplot_gtable(gb)
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid::grid.newpage()
grid::grid.draw(gt)

关于为什么会这样以及如何纠正它的任何想法?如果我取消注释主题参数,我可以接近我想要的,但这会改变绘图区域的纵横比。

标签: rggplot2

解决方案


不确定这是否是您要查找的内容,但您可以使用clip = 'off'option inggplot 3.0.0来显示文本

另请参阅此答案以获取更多信息

# install.packages("devtools")
# devtools::install_github("tidyverse/ggplot2")

library(ggplot2)

g <- ggplot(iris, aes(x = Species, y = Petal.Length)) +
  stat_summary(geom = 'bar', fun.y = mean) +
  geom_point() +
  scale_y_continuous(limits = c(0,8), expand = c(0,0), oob = function(x, ...) x) +
  geom_text(label = 'obText', aes(x = 2, y = 9), check_overlap = TRUE) +
  # this will allow the text outside of the plot panel
  coord_cartesian(clip = 'off') +
  theme(plot.margin = margin(4, 2, 2, 2, "cm"))
g

reprex 包(v0.2.0.9000)于 2018 年 6 月 28 日创建。


推荐阅读