user8270077
user8270077

Reputation: 5091

How to draw a function on a scatter plot in ggplot

I want to plot a function -- e.g. a line-- inside a scatterplot. I have composed code that do both separately but how I can combine them? My experimentations returned error messages.

My code is the following:

library(ROSE)
data(hacide)
train <- hacide.train

Scatter plot

ggplot(train, aes(x1, x2, colour = cls)) +
  geom_point(size = 3, alpha = 0.4)

enter image description here

Line

db <- function(x, beta1, beta2, alpha){-alpha/beta2 - x * beta1/beta2}

ggplot(data.frame(x = c(-4, 4)), aes(x = x))  +
  stat_function(fun = db, args = list(-1.642354, -1.596056, -6.004609), colour = "blue" , size = 2)

enter image description here

But how to superimpose / combine the line with the scatter plot?

Upvotes: 0

Views: 1546

Answers (2)

Numb3rs
Numb3rs

Reputation: 365

The most simple way to do this is just add the function to the original plot. The graphs in ggplot2 are constructed in layers, meaning you can always add more layers while you construct your graphs.

For your code you could either do:

library(ROSE)
data(hacide)
train <- hacide.train

db <- function(x, beta1, beta2, alpha){-alpha/beta2 - x * beta1/beta2}

ggplot(train, aes(x1, x2, colour = cls)) +
  geom_point(size = 3, alpha = 0.4) +
  stat_function(fun = db, args = list(-1.642354, -1.596056, -6.004609),
  colour = "blue" , size = 2)

or add it to the existing plot:

library(ROSE)
data(hacide)
train <- hacide.train

plot = ggplot(train, aes(x1, x2, colour = cls)) +
       geom_point(size = 3, alpha = 0.4)

db <- function(x, beta1, beta2, alpha){-alpha/beta2 - x * beta1/beta2}

plot + stat_function(fun = db, args = list(-1.642354, -1.596056, -6.004609),
colour = "blue" , size = 2)

Upvotes: 2

Paul Endymion
Paul Endymion

Reputation: 561

Is that what you are looking for ?

ggplot(data.frame(x = c(-4, 4)), aes(x = x))  +
  stat_function(fun = db, args = list(-1.642354, -1.596056, -6.004609), colour = "blue" , size = 2)+
  geom_point(data = train, aes(x1, x2, colour = cls),  size = 3, alpha = 0.4)

Upvotes: 1

Related Questions