Facet_wrap就像使用R基础图形的情节

时间:2015-03-18 17:52:24

标签: r plot

我想比较具有相同x和y变量的两个数据集。但是,并非所有X变量点都存在于两者上。作为一个玩具示例说这就是我所拥有的:

position.x <- c(1,2,3)
score.x <- c(450,220,330)

x <- data.frame(position,score.x)

position.y <- c(2,3,5)
score.y <- c(333,423,988)

y<- data.frame(position.y,score.y)

par(mfrow = c(2,1))
plot(x, pch = 19)
plot(y, pch = 19)

enter image description here

X轴无法比较。我找到了一些帖子,解释了如何使用facet_wrap在ggplot上进行操作,但我想使用基本图表来完成。

提前谢谢。

2 个答案:

答案 0 :(得分:2)

如果你要重复这个,你不妨写一些函数(这是ggplot的好处之一 - 它会为你完成所有的设置):

## data needs to be in a long format
dat <- data.frame(position = c(1,2,3,2,3,5),
                  score = c(450,220,330,333,423,988),
                  z = c('x','x','x','y','y','y'))

facet_wrap <- function(data, x, y, z, horiz = TRUE, ...) {
  ## save current par settings and return after finished
  op <- par(no.readonly = TRUE)
  on.exit(par(op))
  zz <- unique(data[, z])

  ## sets up the layout to cascade horizontally or vertically
  ## and sets xlim and ylim appropriately
  if (horiz) {
    par(mfrow = c(1, length(zz)), ...)
    ylim <- range(data[, y])
    xlim <- NULL
  } else {
    par(mfrow = c(length(zz), 1), ...)
    xlim <- range(data[, x])
    ylim <- NULL
  }

  ## make a subset of data for each unique by variable
  ## and draw a basic plot for each one
  for (ii in zz) {
    tmp <- data[data[, z] %in% ii, ]
    plot(tmp[, x], tmp[, y], xlim = xlim, ylim = ylim)
  }
}

facet_wrap(dat, 'position', 'score', 'z', mar = c(5,4,2,2))

enter image description here

facet_wrap(dat, 'position', 'score', 'z', mar = c(5,4,1,2), horiz = FALSE)

enter image description here

答案 1 :(得分:1)

您可以按xlimslim

指定x和y轴的范围
position.x <- c(1,2,3)
score.x <- c(450,220,330)

x <- data.frame(position,score.x)

position.y <- c(2,3,5)
score.y <- c(333,423,988)

y<- data.frame(position.y,score.y)

par(mfrow = c(2,1))
plot(x, pch = 19, xlim=c(1,5))
plot(y, pch = 19, xlim=c(1,5))

enter image description here