简体   繁体   中英

Facet_wrap like plot using R base graphics

I want to compare two datasets with same x and y variables. However, not all X variable points are present on both. As a toy example say this is what I have:

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)

在此输入图像描述

X axes are not comparable. I found some post explaining how to do it on ggplot using facet_wrap but I would like to do it using base graph.

Thank you in advance.

if you are going to repeat this, you might as well write some kind of function (which is one of the benefits of ggplot--it takes care of all the set-up for you):

## 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))

在此输入图像描述

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

在此输入图像描述

you could specify the range of the x and y axises by xlim and slim

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))

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM