Yang Yang
Yang Yang

Reputation: 902

Error when creating a contour plot using ggplot2?

I have a matrix and I want to make a contour plot. At first, I tried the contour function in R, which gives me the plot shown below.

However, the contour lines are not smooth and the x & y labels are not correct. So I want to use ggplot2 to make a smooth contour plot. However, ggplot2 produces an error:

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

The data is available at https://www.dropbox.com/s/1obn2xxcra10usl/data1.rdata?dl=0

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

enter image description here

This is the code I tried to use in 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()

Upvotes: 0

Views: 227

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76460

The error comes from duplicated y values. If you look at the original data1 you will see repeated row names, probably due to rounding or decimals truncation. You must first keep only unique values.

Remove the duplicated y values.

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()

enter image description here

Upvotes: 1

Related Questions