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

ggplot2::stat_density_2d报错:numeric类型无size方法,求无等高线热力图方案

问题解决:stat_density_2d 报错及无等高线热力图生成修正

报错原因

报错ggplot2::stat_density_2d : no method for function ‘size’ for signature "numeric"是由于代码语法错误导致:

  • size(0.01,bins = 16, geom = "polygon")属于错误调用逻辑,这些参数必须直接传递给stat_density_2d函数,不能单独作为图层调用。
  • 代码中使用了不存在的scale_filled_gradient函数,正确函数名称为scale_fill_gradient。

修正后的代码

以下是调整后的完整代码,可生成无等高线的热力图:

myLocation <- "South America"
myMap <- get_map(location = myLocation, zoom = 4, source= "google",
                 maptype= "satellite")
TestData <- read.csv("TestData.csv", header = TRUE, sep = ";", col.names = TRUE)
newsa <- TestData[ ,2:4]

ggmap(myMap, extent = "device") +
  stat_density_2d(
    data = newsa, 
    aes(x = DLongitude, y = DLatitude, fill = stat(density)),
    bins = 16, 
    geom = "polygon",
    color = NA
  ) +
  scale_fill_gradient(low = "transparent", high = "red") +
  scale_alpha(range = c(0, 0.3), guide = FALSE)

关键调整点

  • 将bins、geom等参数整合到stat_density_2d函数内部,删除错误的size()调用;通过color = NA隐藏多边形边框,实现无等高线效果。
  • 在aes映射中添加fill = stat(density),让填充颜色与数据密度值关联,形成热力渐变效果。
  • 替换错误的scale_filled_gradient为scale_fill_gradient,并设置从透明到红色的渐变范围,适配热力图的视觉需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:22:58