我正在使用以下代码来尝试保留超出绘图区域范围的geom元素,但它似乎仍将其裁剪到绘图区域上方一定距离之外。
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)
Run Code Online (Sandbox Code Playgroud)
关于这是为什么以及如何纠正的任何想法?如果我取消对主题参数的注释,则可以接近所需的大小,但这会改变绘图区域的纵横比。
不确定这是否是您要查找的内容,但是您可以使用clip = 'off'option in ggplot 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
Run Code Online (Sandbox Code Playgroud)

由reprex软件包(v0.2.0.9000)于2018-06-28创建。
如果您想查看积分,您可以更改oob =...的值
oob = function(x, ...) xoob = squishoob = censorsquish并且censor是套餐的一部分scales。
请注意两种情况下的均值变化;squish降低6以上的点的值,并censor删除6以上的点。