【问题标题】:Multiple contour plots in the same plot同一图中的多个等高线图
【发布时间】:2015-12-08 08:50:35
【问题描述】:

我是 R 新手,并试图在同一个图中绘制多个 2D 等高线图。我尝试使用以下代码。

dat1 <- structure(list(x1 = c(1:10), y1 = c(10:20)), .Names = c("x1", "y1"), class = "data.frame", row.names = c(NA,-21L))
dat2 <- structure(list(x2 = c(10:20), y2 = c(20:30)), .Names = c("x2", "y2"), class = "data.frame", row.names = c(NA,-21L))
Contourcolors <- colorRampPalette(c('yellow',"red"))(20)
PointColors <- c(rep('green',5),rep('blue',5))
filled.contour(z=dat1,col=Contourcolors,
               plot.axes=points( x=seq(0, 1, length.out = nrow(dat1)),
                                 y=rep(.5,20), 
                                 col=PointColors,cex=5,pch=19)
)
Error in as.matrix.data.frame(x) : 
  length of 'dimnames' [2] not equal to array extent

如何使用 R 轻松做到这一点?

【问题讨论】:

  • 我不确定您要达到什么目的,但 lattice plots 或 ggplot2 plots 在这里可能有用。
  • 你的 dat1 和 dat2 只有 x 和 y 你需要一个 z 才能制作填充轮廓图。这里解释得很好stat.ethz.ch/R-manual/R-devel/library/graphics/html/…
  • 我同意,请检查您的数据。

标签: r ggplot2 contour


【解决方案1】:

我认为您的数据在这里没有多大意义,但也许您正在寻找类似的东西?

dat1 <- data.frame(x = c(0:10), y = c(10:20))
dat2 <- data.frame(x = c(10:20), y = c(20:30))

dat3 <- cbind(rbind(dat1, dat2), df = rep(c('1', '2'), each = 11))

library(ggplot2)
ggplot(dat3, mapping = aes(x, y, col = df)) + 
  geom_density2d()

【讨论】:

  • 感谢您的回答。在我的原始数据中,dat1 和 dat2 中向量的长度是不同的。在那种情况下,我必须写什么而不是 each=11?
  • 类似 rep.int(c('1', '2'), c(nrow(dat1), now(dat2))) 的东西
  • 如果您的意思是 xy 的长度不同(就像您提供的示例数据一样),那么我不明白该图应该显示什么。带有xy 轴的图需要配对数据。您可以排除缺失的数据。
  • 例如。 dat1 中 x 和 y 向量的长度是 36。dat2 中 x 和 y 向量的长度是 68。希望你能理解我的问题。我试过你的代码。但是我在 rep.int(c("1", "2"), c(nrow(dat1), now(dat2))) 中得到了这样的错误:找不到函数“now”
  • 抱歉在我的手机上输入了,应该是rep.int(c("1", "2"), c(nrow(dat1), nrow(dat2)))(我认为很明显)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 2011-04-27
  • 2018-01-23
相关资源
最近更新 更多