R

时间:2015-04-26 12:50:56

标签: r plot

如何使用以下代码在R中的辅助y轴上放置自定义标签?

library(zoo)
#--------------random data
x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-"))
z <- zoo(rnorm(5), x.Date)
z2 <- zoo(rnorm(5, sd = 0.2), x.Date)

#--------------create plot
png(filename = "Google.png", width = 480, height = 480) 

plot(z, type="l", xlab="Year", lt=1, lwd=1, ylab="Google Trend")
grid(nx = NULL, ny = NULL, col = "lightgray", lty = "dotted",
     lwd = par("lwd"), equilogs = TRUE)
par(new=TRUE)
plot(z2, type="l", ann=FALSE, lt=1, lwd=3, yaxt="n")
axis(4, ylab="Test")  # Here?!

legend("topright", c("z", "z2"), lty=c(1,1), 
    lwd=c(1,3),col=c("black","black"),
    box.col="black",bg="white")

title("Google")
dev.off()

标签“测试”没有出现在我的情节......

此外,如何用z2和z线覆盖网格线?换句话说,如何将绘制的线条带到“前面”?

1 个答案:

答案 0 :(得分:2)

您需要mtext才能实现此目的:

library(zoo)
#--------------random data
x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-"))
z <- zoo(rnorm(5), x.Date)
z2 <- zoo(rnorm(5, sd = 0.2), x.Date)

#--------------create plot
#png(filename = "Google.png", width = 480, height = 480) 

plot(z, type="l", xlab="Year", lt=1, lwd=1, ylab="Google Trend")
grid(nx = NULL, ny = NULL, col = "lightgray", lty = "dotted",
     lwd = par("lwd"), equilogs = TRUE)
par(new=TRUE)
plot(z2, type="l", ann=FALSE, lt=1, lwd=3, yaxt="n")
axis(4)  

#------here is the only part I added
#you specify the text, location and usually line=2 to place next to 
#the y-axis labels
mtext('Test', side=4, line=2)
#-----------------------------------    

legend("topright", c("z", "z2"), lty=c(1,1), 
       lwd=c(1,3),col=c("black","black"),
       box.col="black",bg="white")

title("Google")
#dev.off()

输出:

enter image description here

至于z和z2,它们似乎并不在网格线后面。