Search code examples
rggplot2contour

Add Contour Curve to Scatterplot


I am trying to include a rotated parabola on a scatter plot using ggplot. I am able to plot the dataframe and differentiate between the classes, but when I go to plot the boundary curve, which I have here called 'para', I get "object 'category' not found".
Also, when I plot the curve separately, I get the curve. It is when I attempt to add the contour.

What am I missing?

df <- data.frame(
  x = c(-0.674, -1.579, 2.272, 0.974,1.323, -3.953, 1.08, 3.85, 3.543, 0.385),
  y = c(2.771, -0.812, -0.166, -1.489, -2.618, -0.755, 3.5, -1.13, 2.472, -0.211),
  category = c(1,  1,  1,  0,1,  1,  0,  1,  0,  1))

para <- function(x, y) {
  p <- -.1*x^2 - .3 * y^2 + 0.38 * x * y + 0.22 * x + 0.98 * y - 0.1
  return(p)
}


x_values <- seq(min(df$x), max(df$x), length.out = 500)
y_values <- seq(min(df$y), max(df$y), length.out = 500)
grid <- expand.grid(x = x_values, y = y_values)
grid$z <- mapply(para, grid$x, grid$y)


scatter_plot <- ggplot(df, aes(x = x, y = y, color = factor(category))) +
  geom_point() +
  scale_color_manual(values = c("0" = "red", "1" = "blue")) +
  coord_fixed()

contour_plot <- geom_contour(data = grid, aes(x = x, y = y, z = z), breaks = 0, linetype = "solid")

final_plot <- scatter_plot + contour_plot

print(final_plot)

Solution

  • Mapping the color aesthetic specifically in geom_point will let you add the contour plot.

    library(ggplot2)
    
    df <- data.frame(
      x = c(-0.674, -1.579, 2.272, 0.974,1.323, -3.953, 1.08, 3.85, 3.543, 0.385),
      y = c(2.771, -0.812, -0.166, -1.489, -2.618, -0.755, 3.5, -1.13, 2.472, -0.211),
      category = c(1,  1,  1,  0,1,  1,  0,  1,  0,  1))
    
    para <- function(x, y) {
      p <- -.1*x^2 - .3 * y^2 + 0.38 * x * y + 0.22 * x + 0.98 * y - 0.1
      return(p)
    }
    
    x_values <- seq(min(df$x), max(df$x), length.out = 500)
    y_values <- seq(min(df$y), max(df$y), length.out = 500)
    grid <- expand.grid(x = x_values, y = y_values)
    grid$z <- mapply(para, grid$x, grid$y)
    
    scatter_plot <- ggplot(df, aes(x = x, y = y)) +
      geom_point(aes(color = factor(category))) +
      scale_color_manual(values = c("0" = "red", "1" = "blue")) +
      coord_fixed()
    
    contour_plot <- geom_contour(data = grid,
                   aes(x = x, y = y, z = z),
                   breaks = 0, linetype = "solid")
    
    scatter_plot + contour_plot
    

    Alternatively, map color in the ggplot function, and specifically assign a color to the contour:

    scatter_plot <- ggplot(df, aes(x = x, y = y, color = factor(category))) +
      geom_point() +
      scale_color_manual(values = c("0" = "red", "1" = "blue")) +
      coord_fixed()
    
    contour_plot <- geom_contour(data = grid,
                   aes(x = x, y = y, z = z), color = 'orange',
                   breaks = 0, linetype = "solid")
    
    scatter_plot + contour_plot