R - ggplot - stat_contour无法生成等高线 [英] R - ggplot - stat_contour not able to generate contour lines
问题描述
我试图通过 stat_contour()
将等高线添加到我的ggplot / ggplot2-plot中。不幸的是,我不能给你真正的数据,从哪个点值应该评估。然而,另一个容易复制的例子表现相同:
I am trying to add contour lines via stat_contour()
to my ggplot/ggplot2-plot. Unfortunately, I can not give you the real data from which point values should be evaluated. However, another easily repreducably example behaves the same:
testPts <- data.frame(x=rep(seq(7.08, 7.14, by=0.005), 200))
testPts$y <- runif(length(testPts$x), 50.93, 50.96)
testPts$z <- sin(testPts$y * 500)
(ggplot(data=testPts, aes(x=x, y=y, z=z))
+ geom_point(aes(colour=z))
+ stat_contour()
)
这会导致以下错误消息:
This results in the following error message:
Error in if (nrow(layer_data) == 0) return() : argument is of length zero
In addition: Warning message:
Not possible to generate contour data
在我的官方手册/教程中,并且如果我为 stat_contour
提供更多规范,那么看起来并不重要。看起来,该函数并不传递数据(-layer)作为指出错误信息。
The example looks not different to others posted on stackoverflow or in the official manual/tutorial to me, and it seeminlgy doesn't matter if I provide more specifications to stat_contour
. It seems, the function does not pass the data(-layer) as pointed ou tint the error message.
感谢您的想法和建议!
推荐答案
这个问题的一个解决方案是生成一个规则的网格,并且针对该网格插值点值。以下是我为多个数据字段中的一个完成的操作:
One solution to this problem is the generation of a regular grid and the interpolation of point values in respect to that grid. Here is how I did it for just one of multiple data fields:
pts.grid <- interp(as.data.frame(pts)$coords.x1, as.data.frame(pts)$coords.x2, as.data.frame(pts)$GWLEVEL_TI)
pts.grid2 <- expand.grid(x=pts.grid$x, y=pts.grid$y)
pts.grid2$z <- as.vector(pts.grid$z)
这个结果产生一个数据框架,当数据框架定义时,它可以在 stat_contour()
中的ggplot中使用。该函数的参数:
This results in a data frame which can be used in a ggplot in stat_contour()
when defined in the data-parameter of that function:
(ggplot(as.data.frame(pts), aes(x=coords.x1, y=coords.x2, z=GWLEVEL_TI))
#+ geom_tile(data=na.omit(pts.grid2), aes(x=x, y=y, z=z, fill=z))
+ stat_contour(data=na.omit(pts.grid2), binwidth=2, colour="red", aes(x=x, y=y, z=z))
+ geom_point()
)
这个解决方案很可能包含不必要的转换,因为我还不知道更好。此外,我必须为每个数据字段单独进行同一个网格生成,然后再将它们组合到一个数据框中 - 效率并不像我想要的那样适用于更大的数据集。
This solution most likely includes unneccessary transformations because I don't know better yet. Furthermore I must make the same grid generation for every data field individually before combining them in a single data frame again - not as efficient as I would like it to be for bigger data sets.
这篇关于R - ggplot - stat_contour无法生成等高线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!