简体   繁体   中英

R %change from last value on RHS y axis to correspond in position with LHS y axis scale values

I have a plot and can get a LHS y axis and RHS yaxis

x <- rnorm(100)
y <- cumsum(x) 

lastval <- tail(y,1)
pchange <- (y-lastval)*100/lastval
plot(1:100,y)

axis(side = 4) 

However I am trying to show the %change from the last value on the RHS y axis but I am uncertain how to do this. Thank you for your help.

This can be achieved in the following set of steps:

par(mar = c(5, 5, 3, 5)) # right side margin must be adjusted for mtext
plot(1:100, y)
par(new=TRUE)
plot(1:100, pchange, axes = FALSE, ylab="", xlab="") #axes, ylab and xlab prevents overwritting
axis(side = 4) # adds the right scale
mtext("Change in [%]", side=4, line=3) 

EDIT: Values of RHS and LHS are linked:

set.seed(123)
x <- rnorm(100)
y <- cumsum(x) 

lastval <- tail(y,1)
labels <- round(100*(seq(-2,10,2)-lastval)/lastval, 1)

plot(1:100,y, main=(paste("Last Value is ", round(lastval,2))) )
axis(side = 4, at=seq(-2,10,2), labels=labels)
abline(h=seq(-2,10,2), col="grey")
mtext("Change in [%]", side=4, line=3)

在此处输入图片说明

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