Michael
Michael

Reputation: 45

Plotting a function in R

I'm doing QDA on my data and need to plot a decision boundary in R ,or MATLAB, which looks like the function below.

0.651 - 0.728(x_1) - 0.552(x_2) - 0.006(x_1 * x_2) - 0.071(x_1)^2 +.170 (x_2)^2 = 0

Can anyone help me? I've been search the interwebs and can't seem to find the solution.

Upvotes: 1

Views: 165

Answers (2)

jlhoward
jlhoward

Reputation: 59335

Same thing using ggplot:

library(ggplot2)
library(reshape2)   # for melt(...)
## same as first response
x <- seq(0,10,length=1000)
y <- seq(-10,10, length=1000)
z <- outer(x,y,FUN=f)
# need this extra step 
gg <- melt(z, value.name="z",varnames=c("X","Y"))
# creates the plot
ggplot(gg) + stat_contour(aes(x=X, y=Y, z=z), breaks=0)

Upvotes: 1

Martin O&#39;Leary
Martin O&#39;Leary

Reputation: 1266

R doesn't have a function to plot an implicit function like this, but you can fake it pretty well with a contour plot. Assuming you want to plot over the region [0,1]^2 (which can easily be changed), you want some code like this:

#f is your function
f <- function (x_1, x_2) 0.651 - 0.728 * x_1 - 0.552 * x_2 - 0.006 * x_1 * x_2 - 0.071 * x_1^2 +.170 * x_2^2

#length=1000 to be safe, could be set lower
x_1 <- seq(0, 1, length=1000)
x_2 <- seq(0, 1, length=1000)
z <- outer(x_1, x_2, FUN=f)
contour(x_1, x_2, z, levels=0)

Upvotes: 3

Related Questions