Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot min, max, median for each x value in geom_pointrange

Tags:

plot

r

ggplot2

So I know the better way to approach this is to use the stat_summary() function, but this is to address a question presented in Hadley's R for Data Science book mostly for my own curiosity. It asks how to convert code for an example plot made using stat_summary() to make the same plot with geom_pointrange(). The example is:

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

And the plot should look like this:

pointrange plot
(source: had.co.nz)

I've attempted with code such as:

ggplot(data = diamonds, mapping = aes(x = cut, y = depth)) +
  geom_pointrange(mapping = aes(ymin = min(depth), ymax = max(depth)))

enter image description here

However, this plots the min and max for all depth values across each cut category (i.e., all ymin's and ymax's are the same). I also tried passing a vector of mins and maxs, but ymin only takes single values as far as I can tell. It's probably something simple, but I think people mostly use stat_summary() as I've found very few examples of geom_pointrange() usage via Google.

like image 240
user3654634 Avatar asked Feb 04 '17 21:02

user3654634


2 Answers

I think you need to do the summary outside the plot function to use geom_pointrange:

library(dplyr)
library(ggplot2)
summary_diamonds <- diamonds %>% 
    group_by(cut) %>% 
    summarise(lower = min(depth), upper = max(depth), p = median(depth))

ggplot(data = summary_diamonds, mapping = aes(x = cut, y = p)) +
    geom_pointrange(mapping = aes(ymin = lower, ymax = upper))

enter image description here

like image 111
Psidom Avatar answered Nov 15 '22 10:11

Psidom


geom_pointrange includes a stat argument, so you can do the statistical transformation inline https://stackoverflow.com/a/41865061

like image 40
Martin Suchanek Avatar answered Nov 15 '22 09:11

Martin Suchanek