John Gagnon
John Gagnon

Reputation: 915

How to prevent ggplot from clipping points that are out of bounds

I am using the following code to try to preserve geom elements that are out of bounds of the plotting area but it still seems to be clipping them beyond a certain distance above the plotting area.

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)

Any ideas on why this is and how to correct it? If I uncomment the theme argument, I can get close to what I want but this changes the aspect ratio of the plotting area.

Upvotes: 7

Views: 9739

Answers (2)

Tung
Tung

Reputation: 28331

Not sure if this is what you're looking for but you can use clip = 'off' option in ggplot 3.0.0 to get the text show up

See also this answer for more information

# 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

Created on 2018-06-28 by the reprex package (v0.2.0.9000).

Upvotes: 15

sam
sam

Reputation: 541

If you want to see the points, you can change the value of oob =...

oob = function(x, ...) x

enter image description here

oob = squish

enter image description here

oob = censor

enter image description here

squish and censor are part of the scales package.

Note that the mean changes in both cases; squish lowers the value of the points above 6, and censor removes the points above 6.

Upvotes: 2

Related Questions