Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: ggplot2 pointrange example

I am currently reading R for Data Science by Hadley Wickham. In that, there is the following example:

library(tidyverse)

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

Now, there is a question as how to create the same plot by using appropriate geom_ function. I looked at the default geom for stat_summary and it is pointrange.

So I tried the following:

ggplot(data = diamonds) + geom_pointrange(mapping = aes(x = cut, y = depth), stat = "summary")

But I do not get the min and max points on the plot.

How do I get the exact plot by using geom_pointrange?

like image 654
chintan s Avatar asked Jan 25 '17 11:01

chintan s


People also ask

How do I make Ggplot error bars smaller?

Specify ymin = len-sd and ymax = len+sd to add lower and upper error bars. If you want only to add upper error bars but not the lower ones, use ymin = len (instead of len-sd ) and ymax = len+sd .

How do I get rid of error bars in R?

The width in the errorbar geom controls the width of the horizontal end bars, so set that to 0 to remove the end bars.

Which argument of Ggplot can be used to add Customisation to plots?

To customize the plot, the following arguments can be used: alpha, color, fill and dotsize. Learn more here: ggplot2 dot plot.

Which layer in ggplot2 controls the appearance of plot?

The aesthetic layer maps variables in our data onto scales in our graphical visualization, such as the x and y coordinates. In ggplot2 the aesthetic layer is specified using the aes() function. Let's create a plot of the relationship between Sepal.


2 Answers

geom_pointrange does not automatically compute the ymin or ymax values. You can do this with stat = "summary" while still using geom_pointrange:

ggplot(data = diamonds) +
  geom_pointrange(mapping = aes(x = cut, y = depth),
                  stat = "summary",
                  fun.ymin = min,
                  fun.ymax = max,
                  fun.y = median)
like image 54
Ben Herbertson Avatar answered Nov 16 '22 02:11

Ben Herbertson


The easy way I can think of is just using geom_line and stat_summary

 ggplot(data = diamonds, mapping = aes(x = cut, y = depth)) +
     geom_line() +
     stat_summary(fun.y = "median", geom = "point", size = 3)

This will give very similar plot. enter image description here

If I really want to use geom_pointrange, I would make small dataset first.

data = diamonds %>%
    group_by(cut) %>%
    summarise(min = min(depth), max = max(depth), 
        median = median(depth))

ggplot(data, aes(x = cut, y = median, ymin = min, ymax = max)) + 
    geom_linerange() + 
    geom_pointrange()

This would generate the exact same plot. Hope this helps! enter image description here

like image 20
JennyStat Avatar answered Nov 16 '22 01:11

JennyStat