How to share the same X axis in a combined plot without ggplot2?

Viewed 37

I'm trying to combine two time series into a plot sharing the same values of the X axis. When I use the code below I got these goals. However, I'd like to display just one X axis for both the series and I also would like to remove the Y axis in the right side of the plot. My dataset is two financial variables from Yahoo Finance. I use the 'quantmod' package to extract the data and the default function 'plot' to visualize the series in the way that I want to.

PS: I got some results using the package 'ggplot2', but they don't fit well to my aim.

install.packages('quantmod')
library(quantmod)

## Get the data

# OVX
getSymbols(Symbols = "^OVX", from = "2007-05-10", 
           to = "2020-01-01", src = "yahoo")

# USO
getSymbols(Symbols = "USO", from = "2007-05-10", 
           to = "2020-01-01", src = "yahoo")


## PLOTS

par(mfcol=2:1, xaxt = "s")
plot(USO[, "USO.Adjusted"], main="USO", type = "l", lwd = 0.7, grid.col = NA, axes = F)

plot(OVX[, "OVX.Adjusted"], main="OVX", type = "l", lwd = 0.2, grid.col = NA)

I'm not allowed to insert images here yet, then there is a link below to see my plot.

Both Series Plotted

1 Answers

plot.xts becomes aware of your "xts" class. To avoid this, use plot.default and lines.default, then you may easily add axis, mtext etc.

plot.default(USO$USO.Adjusted, col=2, type="l", xaxt='n',
             main='My TS PLot', xlab='Date', ylab='Unit',
             ylim=c(-10, max(USO[, "USO.Adjusted"])))
axis(1, axTicks(1), labels=F)
mtext(strftime(index(USO), '%b %y')[axTicks(1) + 1], 1, 1, at=axTicks(1))
lines.default(OVX$OVX.Adjusted, col=3)
abline(h=0, lty=3)
legend('topright', lty=1, col=2:3, legend=c("USO", "OVX"))

enter image description here

However, the added OVX is tiny and almost invisible. You could magnify the values and use a secondary y-axis, e.g.:

plot.default(USO$USO.Adjusted, col=2, type="l", axes=F,
             main='My TS PLot', xlab='Date', ylab='Unit', 
             ylim=c(-10, max(USO[, "USO.Adjusted"]) + 100))
axis(1, axTicks(1), labels=F)
mtext(strftime(index(USO), '%b %y')[axTicks(1) + 1], 1, 1, at=axTicks(1))
axis(2, axTicks(2), labels=F, col=2)
mtext(axTicks(2), 2, 1, at=axTicks(2), col=2)
axis(4, axTicks(2), labels=F, col=3)
mtext((0:5)*20, 4, 1, at=(0:5)*200, col=3)
lines.default(OVX$OVX.Adjusted*10, col=3)
abline(h=0, lty=3)
legend('topright', lty=1, col=2:3, legend=c("USO", "OVX"))
box()

enter image description here

Related