Skip to content
Prev 381843 / 398502 Next

Stacking two graphs with different x and y scale on the same graph

Hi

In ancient times I developped function plot.yy which requires some data twisting but should do plotting with one x axis and two y axes and should estimete ranges automatically.

datA <- data.frame(datum=x1, counts=y1)
datA$vzor <- "A"
datB <- data.frame(datum=x2, counts=y2)
datB$vzor <- "B"
mydat <- merge(datA, datB, all=T, by="datum")

plot.yy(mydat$datum, mydat$counts.x, mydat$counts.y, col=c("red", "blue"), linky=T)


## The function is currently defined as
plot.yy <- function (x, yright, yleft, yleftlim = NULL, yrightlim = NULL, 
    xlab = NULL, yylab = list(NA, NA), pch = c(1, 2), 
    col = c(1,2), linky = F, smooth = 0, lwds = 1, length = 10, 
        format = "%d/%m", rect = NULL, type = "p", ...) 
{
    par(mar = c(5, 4, 4, 2), oma = c(0, 0, 0, 3))
    plot(x, yright, ylim = yrightlim, axes = F, ylab = "", xlab = xlab, 
        pch = pch[1], col = col[1], type = type, ...)
    if (!is.null(rect)) 
        rect(x[rect[1]], rect[2], x[rect[3]], rect[4], col = "grey")
    points(x, yright, ylim = yrightlim, ylab = "", xlab = xlab, 
        pch = pch[1], col = col[1], ...)
    axis(4, pretty(range(yright, na.rm = T), 10), col = col[1])
    if (linky) 
        lines(x, yright, col = col[1], ...)
    if (smooth != 0) 
        lines(supsmu(x, yright, span = smooth), col = col[1], 
            lwd = lwds, ...)
    if (is.na(yylab[[1]])) 
        mtext(deparse(substitute(yright)), side = 4, outer = T, 
            line = 1, col = col[1], ...)
    else mtext(yylab[[1]], side = 4, outer = T, line = 1, col = col[1], 
        ...)
    par(new = T)
    plot(x, yleft, ylim = yleftlim, ylab = "", axes = F, xlab = xlab, 
        pch = pch[2], col = col[2], ...)
    box()
    axis(2, pretty(range(yleft, na.rm = T), 10), col = col[2], 
        col.axis = col[2])
    if (!inherits(x, c("Date", "POSIXt"))) 
        axis(1, pretty(range(x, na.rm = T), 10))
    else {
        if (inherits(x, "POSIXt")) {
            l <- length(x)
            axis(1, at = x[seq(1, l, length = length)], 
            labels = format(as.POSIXct(x[seq(1,l, length = length)]), 
            format = format))
        }
        else {
            if (inherits(x, "Date")) {
                l <- length(x)
                axis(1, at = x[seq(1, l, length = length)], 
                labels = format(as.Date(x[seq(1,l, length = length)]), 
                format = format))
            }
            else {
                print("Not suitable x axis")
            }
        }
    }
    if (is.na(yylab[[2]])) 
        mtext(deparse(substitute(yleft)), side = 2, line = 2, 
            col = col[2], ...)
    else mtext(yylab[[2]], side = 2, line = 2, col = col[2], 
        ...)
    if (linky) 
        lines(x, yleft, col = col[2], lty = 2, ...)
    if (smooth != 0) 
        lines(supsmu(x, yleft, span = smooth), col = col[2], 
            lty = 2, lwd = lwds, ...)