You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggplot为散点图添加旋转抛物线轮廓时遇‘category未找到’错误

问题:ggplot添加轮廓曲线时出现「object 'category' not found」错误

使用ggplot绘制带类别区分的散点图时正常,但添加自定义抛物线轮廓(para函数生成)时,抛出「object 'category' not found」错误。单独绘制轮廓曲线无问题,仅在与散点图叠加时出错。

用户提供的代码:

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)

原因分析

ggplot会默认继承主图层的美学映射(aes)。主图的aes中设置了color = factor(category),但用于绘制轮廓的grid数据框中并没有category列,因此叠加时会因找不到该变量而报错。

解决方法

有两种简单的修复方式:

方式1:禁用美学映射继承

在geom_contour中添加inherit.aes = FALSE,明确告诉该图层不继承主图的美学映射:

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

方式2:覆盖color映射

直接为轮廓曲线指定颜色,或在aes中重置color参数,避免继承主图的color映射:

# 直接指定轮廓颜色
contour_plot <- geom_contour(data = grid, aes(x = x, y = y, z = z), breaks = 0, linetype = "solid", color = "black")

# 或在aes中重置color
contour_plot <- geom_contour(data = grid, aes(x = x, y = y, z = z, color = NULL), breaks = 0, linetype = "solid")

修改后重新运行代码,即可正常显示散点图与轮廓曲线的叠加效果。

内容的提问来源于stack exchange,提问作者gunsnfloyd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:25:24