Is there a way to align 2 independent axes in an R graph?

后端 未结 2 1621
孤城傲影
孤城傲影 2021-01-25 16:07

I\'m plotting a graph with different axis. The problem is that I want the 2 axes to be crossing one point, the rest doesn\'t really matter. Is it possible?

Here is a rep

2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 17:07

    It's not a beautiful solution, but as long as your x-axes always cross the 0 value, you can set the xlim=c(-max(c(-min(x),max(x))),max(c(-min(x),max(x)))) for both plots. This will make the x-axis always center at 0for both the top and bottom axes. The same can be done with the y-axes if you so choose.

    # Set graphing parameters
    par(mar = c(5,4,4,4) + 0.1) # This can be reset later with "dev.off()"
    
    # Plot the first graph
    plot(x = -10:10, y = -10:10, 
         xlim=c(-max(c(-min(x),max(x))),max(c(-min(x),max(x)))),
         xlab="x-label-1",ylab="y-label-1") # Added labels to be changed
    abline(v=0,lty = 2)
    
    # Plot the second graph using new axes
    par(new =TRUE)
    plot(x = -10:50, y = seq(-5,5,length.out = length(-10:50)), 
         xaxt = "n", yaxt = "n", bty ="n",
         xlim=c(-max(c(-min(x),max(x))),max(c(-min(x),max(x)))),
         xlab=NA,ylab=NA) # Remove x- and y-axis labels
    abline(v=0,lty = 3)
    axis(3, col="red",col.axis="red",las=2, cex.axis = 1)
    axis(4, col="red",col.axis="red",las=2, cex.axis = 1)
    mtext("x-label-2", side = 3, line = 3, cex = par("cex.lab")) # Labeled secondary x-axis
    mtext("y-label-2", side = 4, line = 3, cex = par("cex.lab")) # Labeled secondary y-axis
    

    which gives:

    I hope this works! You'll need to play around with the values for par(mar()) if you want to label your graphs with a title.

提交回复
热议问题