plot – Problems with second Y axis plotting two time series. R studio

I’m trying to plot two different y-axis. My effort:

Note, TMax_trend and TMin_trend' are time series defined as:

data(SeatacWeather, package="latticeExtra")
calendar = seq(as.Date("2007/1/1"), as.Date("2007/3/31"), by = "day")

Table.dt = data.frame("DateYMD" = calendar, 'T_Max' = SeatacWeather$max.temp, 'T_Min' = SeatacWeather$min.temp)


TMax_ts <- ts(Table.dt[,2], start = c(2007, 1, 1), end = c(2007, 31, 3), frequency = 3)
TMax_ts_dec <- decompose(TMax_ts)
TMax_trend <- TMax_ts_dec$trend

TMin_ts <- ts(Table.dt[,3], start = c(2007, 1, 1), end = c(2007, 31, 3), frequency = 3)
TMin_ts_dec <- decompose(TMin_ts)
TMin_trend <- TMin_ts_dec$trend

Trying to plot with the same x-axis:

par(mar = c(5, 4, 4, 4) + 0.3)              # Additional space for second y-axis
plot(TMin_trend, col="#9933CC")                      # Create first plot
par(new = TRUE)                             # Add new plot
plot(TMax_trend, col="#FF9933",                      # Create second plot without axes
     axes = FALSE, xlab = "", ylab = "")
axis(side = 4, at = pretty(range(TMax_trend)))      # Add second axis 
mtext("TMax_trend", side = 4, line = 3)             # Add second axis label
legend('topright', legend=c("TMin_trend", "TMax_trend"),
       col=c("#9933CC", "#FF9933"), lty=1:1, cex=0.5)

But it doesn’t plot the second y-axis defined with pretty(range(TMax_trend)). Altought, this is toy data, I need TMax and TMin variables to be time series objets. Do you know any way to plot with two y-axis and legend?

Read more here: Source link