我试图用ggplot2绘制轮廓图,事实证明它比我想象的要困难一些.使用iris数据集,我能够生成这个图:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_density2d(geom="polygon", aes(fill=..level..))
Run Code Online (Sandbox Code Playgroud)
我的问题是我似乎无法弄清楚如何显示 - 而不是密度值 - 原始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..))
Run Code Online (Sandbox Code Playgroud)
这会产生一个特别奇怪的错误消息:
Warning message:
Computation failed in `stat_contour()`:
(list) object cannot be coerced to type 'double'
Run Code Online (Sandbox Code Playgroud)
我也试过这个:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_density2d(geom="polygon", aes(fill=Sepal.Width))
Run Code Online (Sandbox Code Playgroud)
最后这个:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
geom_tile()
Run Code Online (Sandbox Code Playgroud)
任何人都可以推荐一个很好的方法来生成ggplot2中的等高线图,变量的值本身会产生轮廓的水平吗?
更新
从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..))
Run Code Online (Sandbox Code Playgroud)
工作得很好,看起来很棒.但是,如果我将这完全应用于iris示例,如下所示:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_contour(geom="polygon", aes(fill=..level..))
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
Warning message:
Computation failed in `stat_contour()`:
(list) object cannot be coerced to type 'double'
Run Code Online (Sandbox Code Playgroud)
这些都是具有相似结构的数据帧,因此我无法弄清楚导致此问题的两者之间有什么不同.
这种方式的最终解决方案是使用akima包进行插值然后ggplot2进行最终绘图.这是我使用的方法:
library(ggplot2)
library(akima)
library(dplyr)
interpdf <-interp2xyz(interp(x=iris$Petal.Width, y=iris$Petal.Length, z=iris$Sepal.Width, duplicate="mean"), data.frame=TRUE)
interpdf %>%
filter(!is.na(z)) %>%
tbl_df() %>%
ggplot(aes(x = x, y = y, z = z, fill = z)) +
geom_tile() +
geom_contour(color = "white", alpha = 0.05) +
scale_fill_distiller(palette="Spectral", na.value="white") +
theme_bw()
Run Code Online (Sandbox Code Playgroud)