简体   繁体   中英

How to draw a function on a scatter plot in ggplot

I want to plot a function -- eg 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)

在此处输入图片说明

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)

在此处输入图片说明

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

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)

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)

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