gpt4 book ai didi

r - 与 ggplot2 中的变量级别相对应的等高线级别

转载 作者:行者123 更新时间:2023-12-01 17:33:27 24 4
gpt4 key购买 nike

我正在尝试用 ggplot2 绘制等高线图,事实证明它比我想象的要困难一些。使用 iris 数据集我能够生成此图:

ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_density2d(geom="polygon", aes(fill=..level..))

enter image description here

我的问题是,我似乎无法弄清楚如何显示原始 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 中生成等值线图的好方法,其中变量本身的值产生等值线的级别吗?

已更新

来自 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'

这些都是具有相似结构的数据帧,因此我无法弄清楚导致此问题的两者之间有什么不同。

最佳答案

这种方式的最终解决方案是使用 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()

enter image description here

关于r - 与 ggplot2 中的变量级别相对应的等高线级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35593967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com