简体   繁体   English

如何在ggplot中的散点图上绘制函数

[英]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. ggplot2中的图形是ggplot2构建的,这意味着您可以在构建图形时始终添加更多层。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM