13

how to change the lower and upper point in this stat summary plot to 25% quartile and 75% quartile?

ggplot(data = diamonds) + stat_summary(
  mapping = aes(x = cut, y = depth),
  fun.ymin = min,
  fun.ymax = max,
  fun.y = median
)

3 Answers 3

20
ggplot(data = diamonds) + stat_summary(
  mapping = aes(x = cut, y = depth),
  fun.min = function(z) { quantile(z,0.25) },
  fun.max = function(z) { quantile(z,0.75) },
  fun = median)

Diamonds

Sign up to request clarification or add additional context in comments.

5 Comments

HI,@DomQ I crossed this answer and it helped me a lot. Can I ask for a clarification? fun.min receives a vector and returns a number, how does function() knows that you are passing Depth. is the dependent variable y being pass by default? Thanks a lot
@spleen ggplot will apply fun.min to its y value (which was specified as depth). The default function that is used is min, but defining fun.min like this allows the use of a different function. ggplot knows to apply fun.min to its y value.
what is z in this answer? I'm trying to adapt this to a slightly different plot, but I have no idea how to specify that the function should be applied to the x value.
@tnt z is just a placeholder variable. I am defining functions to get the upper and lower limit for the bars in the graph.
@G5W I can't get this solution to work for me: stackoverflow.com/questions/78208127/…
11

Rewriting G5W's solution, using the geom function instead of the stat function:

ggplot(data = diamonds) +
  geom_pointrange(mapping = aes(x = cut, y = depth),
                  stat = "summary",
                  fun.min = function(z) {quantile(z,0.25)},
                  fun.max = function(z) {quantile(z,0.75)},
                  fun = median)

enter image description here

Comments

2

This question already has excellent answers, but I wanted to build on these with more brief solution, as I prefer to keep code for plots short. stat_summary can take custom functions, with support for arguments.

library(ggplot2)

# Define function to calculate IQR at given quantiles
iqr = function(z, lower = 0.25, upper = 0.75) {
  data.frame(
    y = median(z),
    ymin = quantile(z, lower),
    ymax = quantile(z, upper)
  )
}

# Plot standard IQR
ggplot(data = diamonds, mapping = aes(x = cut, y = depth)) + 
  stat_summary(fun.data = iqr)

# Arguments can be accessed with fun.args
ggplot(data = diamonds, mapping = aes(x = cut, y = depth)) + 
  stat_summary(fun.data = iqr, fun.args = list(lower = 0.1, upper = 0.9))

Created on 2022-08-29 by the reprex package (v2.0.0)

Comments

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.