r - 如何防止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)
关于为什么会这样以及如何纠正它的任何想法?如果我取消注释主题参数,我可以接近我想要的,但这会改变绘图区域的纵横比。
解决方案
不确定这是否是您要查找的内容,但您可以使用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 日创建。
推荐阅读
- react-native - React 本机项目在 iOS 中不起作用。如何重写 iOS 配置?
- django - django-tables2 分页菜单对于移动设备来说太长并且溢出
- scala - 按索引访问 RDD 元素
- python - 将 bash 脚本的结果捕获到 Python 程序中
- javascript - 如何使用javascript从字符串中删除完整的标签?
- scala - 如何避免在循环中分配的var
- docker - 无法在 Crafter CMS 3.1.0 中创建网站
- python - 如何在现有文件 .csv 的头部添加一些文本而不覆盖?
- python - Beautiful Soup 没有提供任何东西,尽管存在价值
- java - Spark rdd 使用 collect 方法生成 OutOfMemoryError