简体   繁体   中英

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

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 http://r4ds.had.co.nz/visualize_files/figure-html/unnamed-chunk-35-1.png

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)))

在此输入图像描述

However, this plots the min and max for all depth values across each cut category (ie, 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.

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))

在此输入图像描述

geom_pointrange包含一个stat参数,因此你可以在线进行统计转换https://stackoverflow.com/a/41865061

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM