R: ggplot2 line example

I am currently reading R for Hadley Wickham data science . This example has 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 the question is how to create the same graph using the corresponding geom_ function. I looked at the default geom for stat_summary and this 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 chart.

How to get an accurate graph using geom_pointrange ?

+5
source share
2 answers

geom_pointrange does not automatically calculate ymin or ymax values. You can do this with stat = "summary" while continuing to use geom_pointrange :

 ggplot(data = diamonds) + geom_pointrange(mapping = aes(x = cut, y = depth), stat = "summary", fun.ymin = min, fun.ymax = max, fun.y = median) 
+6
source

The easy way I can think of is to just use 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 a very similar plot. enter image description here

If I really want to use geom_pointrange, I first create a small dataset.

 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 will create an accurate plot. Hope this helps! enter image description here

+3
source

Source: https://habr.com/ru/post/1263323/


All Articles