Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a ggplot2 stat_function to an existing graph

Tags:

r

ggplot2

I've got a graph and I'd like to superimpose a functional form over the graph. Seems straight forward, but I'm missing something. Here's my example data and illustration where I use stat_function to try and add f1 to the graph:

library(ggplot2)
sample_data <- data.frame(rate  = c(0.514492753623188, 0.553072625698324, 0.656527249683143, 0.675694939415538,
                                    0.68681076312307, 0.715657311669128, 0.792349726775956), 
                          level = c(0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85) )

f1 <- function(x) pbeta(x, shape1=1.01, shape2=.9 ) * 100

g <- ggplot() +
  geom_line(aes(y = rate*100 , x = level), 
            data = sample_data, stat="identity") +
  stat_function(fun = f1) 
g

As you can see, the f1 line is not there.

So as an alternative, I can add the points to the initial data.frame and then plot them with geom_line as the following example illustrates:

## add f1 to data.frame
sample_data$f1 <- f1(sample_data$level )

g <- ggplot() +
  geom_line(aes(y = rate*100 , x = level), 
            data = sample_data, stat="identity") +
  geom_line(aes(y = f1 , x = level), 
   data = sample_data, stat="identity", color='red')
g

So that works, and gets me what I need, but I can't figure out why stat_function didn't work. Any tips?

like image 886
JD Long Avatar asked May 20 '18 17:05

JD Long


People also ask

Can you use two datasets in ggplot?

This example explains how to draw a ggplot2 plot based on two different data sources. For this, we have to set the data argument within the ggplot function to be equal to NULL, and then we have to specify the two different data frames within two different calls of a geom_ function (in this case geom_point).

What does stat_function do in R?

stat_function() computes the following variables: x. x values along a grid. y.

Which operator allows you to add objects to a ggplot?

Elements that are normally added to a ggplot with operator + , such as scales, themes, aesthetics can be replaced with the %+% operator.


1 Answers

You need data = sample_data, aes(y = rate*100 , x = level) in your first ggplot call so stat_function knows about the data are being used

library(ggplot2)

sample_data <- data.frame(rate  = c(0.514492753623188, 0.553072625698324, 0.656527249683143, 0.675694939415538,
                                    0.68681076312307, 0.715657311669128, 0.792349726775956), 
                          level = c(0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85) )

f1 <- function(x) pbeta(x, shape1=1.01, shape2=.9 ) * 100

g <- ggplot(data = sample_data, aes(y = rate*100 , x = level)) +
  geom_line() +
  stat_function(fun = f1, color = "red")
g

Created on 2018-05-20 by the reprex package (v0.2.0).

like image 71
Tung Avatar answered Sep 25 '22 11:09

Tung