【问题标题】:Error when creating a contour plot using ggplot2?使用 ggplot2 创建等高线图时出错?
【发布时间】:2019-03-22 03:10:44
【问题描述】:

我有一个矩阵,我想制作一个等高线图。起初,我尝试了 R 中的 contour 函数,得到了下图。

但是,轮廓线不平滑,x & y 标签也不正确。所以我想用ggplot2 来制作一个平滑的等高线图。但是,ggplot2 会产生错误:

Computation failed in `stat_contour()`:
  Contour requires single `z` at each combination of `x` and `y`.

数据可在https://www.dropbox.com/s/1obn2xxcra10usl/data1.rdata?dl=0获取

load("data1.rdata",.GlobalEnv)
contour(data1)

这是我在ggplot2中尝试使用的代码:

library(reshape2)
library(ggplot2)
data1_melt = melt(data1)
names(data1_melt) <- c("y", "x", "pr")

ggplot(data1_melt, aes(x = x, y = y, z = pr)) + stat_contour()

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    错误来自重复的y 值。如果您查看原始的data1,您会看到重复的行名,可能是由于舍入或小数截断。您必须首先只保留唯一值。

    删除重复的y 值。

    sp <- split(data1_melt, data1_melt$x)
    sp <- lapply(sp, function(DF) {
      i <- !duplicated(DF[["y"]])
      DF[i, ]
    })
    
    data1_melt <- do.call(rbind, sp)
    rm(sp)
    
    ggplot(data1_melt, aes(x = x, y = y, z = pr)) +
      geom_contour()
    

    【讨论】:

    • 感谢您的帮助。但是,我的数据实际上包含重复值,我们该如何处理呢?另外,您制作的等高线图仍然不平滑,您能解决这个问题吗?非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多