2015-04-26 120 views
1

如何使用以下代碼在R中的輔助y軸上放置自定義標籤?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線網格線?換句話說,如何將繪製的線條帶到「前面」?

回答

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他們不似乎是這裏的網格線後面。

+0

恩,謝謝你這個快速的回答!奇怪的是:如果我創建了這個陰謀,這是行不通的。 雖然z行在網格線後面... –

+0

如果我使用'line = 0'或'line = 1',但只有在錯誤的位置,我才能看到「測試」。 –

+1

嘗試使用'par(mar = c(5,4,4,2)'(在繪圖函數之前使用這個函數)來更改兩個繪圖的邊距,並查看哪一個最適合您。這在使用rstudio的查看器時很典型, png。每個值對應於圖的每一邊,增加數字以縮小圖,以便看到標籤 – LyzandeR