我正在尝试用 ggplot2 绘制等高线图,事实证明它比我想象的要困难一些。使用iris
数据集我能够生成这个图:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_density2d(geom="polygon", aes(fill=..level..))
我的问题是我似乎无法弄清楚如何显示原始数据而不是密度值Sepal.Width
价值观。这是我尝试过的:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, z=Sepal.Width)) +
geom_tile(aes(fill=Sepal.Width))+
stat_contour(aes(colour=..level..))
这会产生一个特别奇怪的错误消息:
Warning message:
Computation failed in `stat_contour()`:
(list) object cannot be coerced to type 'double'
我也尝试过这个:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_density2d(geom="polygon", aes(fill=Sepal.Width))
最后这个:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
geom_tile()
谁能推荐一种在 ggplot2 中生成等值线图的好方法,其中变量本身的值产生等值线的级别?
UPDATED
来自stat_contour
例子:
# Generate data
library(reshape2) # for melt
volcano3d <- melt(volcano)
names(volcano3d) <- c("x", "y", "z")
# Basic plot
ggplot(volcano3d, aes(x, y, z = z)) +
stat_contour(geom="polygon", aes(fill=..level..))
工作得很好,看起来也很棒。但如果我将其完全应用于虹膜示例,如下所示:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_contour(geom="polygon", aes(fill=..level..))
我收到此错误消息:
Warning message:
Computation failed in `stat_contour()`:
(list) object cannot be coerced to type 'double'
这些都是具有相似结构的数据帧,因此我无法弄清楚导致此问题的两者之间有什么不同。