1

I am trying to display conditional error bars, for example, when I ran this I see the error bars for all values.

d <- qplot(cyl, mpg, data=mtcars)
d + stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar")

I would like to display the above error bars only if N > than a specified value. Is there a way of doing this?

1 Answer 1

2

Sure, you could build function factories for the fun.ymin and fun.ymax arguments that only give the value if the input length exceeds some number. The only downside is though that it has to return some value, so you'll get a warning about that.


library(ggplot2)

nmax <- function(n) {
  n <- force(n)
  function(x) {
    if (length(x) >= n) {
      max(x)
    } else {
      NA_real_
    }
  }
}

nmin <- function(n) {
  n <- force(n)
  function(x) {
    if (length(x) >= n) {
      min(x)
    } else {
      NA_real_
    }
  }
}

d <- qplot(cyl, mpg, data=mtcars)
d + stat_summary(fun.ymin = nmin(8), fun.ymax = nmax(8), geom = "errorbar")
#> Warning: Removed 1 rows containing missing values (geom_errorbar).

Created on 2020-05-06 by the reprex package (v0.3.0)

If you find that specifying N two times is too cumbersome / error prone, you can also make regular functions that take n as an argument and pass fun.args:

nmax2 <- function(x, n) {
  if (length(x) >= n) {
    max(x)
  } else {
    NA_real_
  }
}

nmin2 <- function(x, n) {
  if (length(x) >= n) {
    min(x)
  } else {
    NA_real_
  }
}

d <- qplot(cyl, mpg, data=mtcars)
d + stat_summary(fun.ymin = nmin2, fun.ymax = nmax2, fun.args = list(n = 8), geom = "errorbar")
Sign up to request clarification or add additional context in comments.

3 Comments

Alternatively, pass a subset of the data to stat_summary using the data argument. For example use data = . %>% group_by(cyl) %>% filter(n() >= 8)
@Axeman Hi! I am trying to use this solution. However, instead of passing a fixed argument to my functions I would like to pass the value of the dots that I am plotting. This is my code: ggplot(data=chr1, aes(x=x_values0, y=AF))+ geom_point(aes(col=color), size=2)+ stat_summary(aes(fun.ymin = ymin(AF, sdPopHetAF), fun.ymax = ymax(AF, sdPopHetAF)), geom = "errorbar") AF and sdPopHetAF are variables from chr, the dataframe indicated in the beginning. However, it is not detecting this variables and not working. How can I solve this?
@Jeni, it's better if you ask a new question, and show a reproducible example of your problem. I don't see anything obviously wrong, other than your code has chr1 as data, but you say your data is chr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.