Home > OS >  Clip {ggdist} ccdf-barplot
Clip {ggdist} ccdf-barplot

Time:03-14

I'm making a complementary cumulative distribution function barplot with {ggdist}. When I export the plot to svg (or other vector representation), I notice that there is a zero-width stripe protruding from the polygon (see attached image). I rather not have this protruding stripe.

library(ggplot2)
library(ggdist)

df <- data.frame(
  x = rep(c("A", "B"), each = 10),
  y = c(rnorm(20, mean = rep(c(5, 7), each = 10)))
)

p <- ggplot(df, aes(x, y))  
  stat_ccdfinterval(geom = "slab")  
  lims(y = c(0, NA))

ggsave("test.svg", plot = p, device = svglite::svglite)

The code above results in an svg file below, wherein I've highlighted the outline of the polygon with the stripe.

enter image description here

I'd like to get rid of that zero-width stripe. I tried setting the relevant aesthetic to NA at these points, but that also deletes one of the corners that is not part of the stripe.

ggplot(df, aes(x, y))  
  stat_ccdfinterval(
    geom = "slab", 
    aes(thickness = after_stat(ifelse(f == 0, NA, f)))
  )  
  lims(y = c(0, NA))

Created on 2022-03-10 by the reprex package (v2.0.1)

CodePudding user response:

I found a solution specific to this problem, but it might pan out differently if the orientation is horizontal or the cdf instead of the ccdf is used. In brief, we're still setting 0-thickness datapoints to NA, but we now do this only where the y aesthetic exceeds the groupwise maximum.

library(ggplot2)
library(ggdist)

df <- data.frame(
  x = rep(c("A", "B"), each = 10),
  y = c(rnorm(20, mean = rep(c(5, 7), each = 10)))
)

helper <- function(f, y, group) {
  split(f, group) <- Map(
    function(value, y) {
      f <- value
      max_y <- max(y[f != 0])
      f[f == 0 & y > max_y] <- NA
      f
    },
    value = split(f, group),
    y     = split(y, group)
  )
  f
}

ggplot(df, aes(x, y))  
  stat_ccdfinterval(
    geom = "slab", 
    aes(thickness = after_stat(helper(f, y, group)))
  )  
  lims(y = c(0, NA))

Created on 2022-03-13 by the reprex package (v2.0.1)

  • Related