2017-04-12 86 views
0

讓我們考慮下述R代碼曲線:在一個圖形圖像多於兩條曲線,用具有不同範圍

x=seq(1,10,1) 
y1=runif(10,0,1) 
y2=runif(10,0,1) 
y3=runif(10,100,200) 
matplot(x,cbind(y1,y2,y3),type="l") 

這裏,y1y2的範圍是從的y3不同。因此,當我創建此matplot時,y1y2的曲線在底部呈直線,而對應於y3的曲線沒有問題。

有沒有什麼方法可以在同一個圖表中正確繪製範圍很大的曲線?

回答

1

簡單的方法是使用對數刻度Y軸:

matplot(seq(1, 10, 1), cbind(runif(10, 0, 1), runif(10, 0, 1), runif(10, 100, 200)), 
     type = "l", log = "y") 

結果: enter image description here

可以使用ggplot2實現了類似的結果:

library(tidyr) 
library(ggplot2) 
df1 = data.frame(x = seq(1, 10, 1), 
       y1 = runif(10, 0, 1), 
       y2 = runif(10, 0, 1), 
       y3 = runif(10, 100, 200)) 

df1 %>% 
    gather(y, value, -x) %>% 
    ggplot(aes(x, value)) + geom_line(aes(color = y)) + scale_y_log10() 

結果: enter image description here

如果你不想登錄軸,另一種選擇是用面無軸標:

df1 %>% 
    gather(y, value, -x) %>% 
    ggplot(aes(x, value)) + geom_line() + facet_grid(y ~ ., scales = "free") 

結果: enter image description here

1

有大量的有兩個繪製一個圖的周圍很好的例子不同的尺度,例如https://www.r-bloggers.com/r-single-plot-with-two-different-y-axes/但是,這些通常需要使用par(new=t),這通常需要一點調整,即對於數據探索而言並不總是直觀的。

我會建議使用ggplotfacet_wrap繪製的線條勾勒出在不同的幀在同一圖像上:

library(ggplot2) 
out <- data.frame(x=rep(x,3), y=c(y1, y2, y3), gp=unlist(lapply(c("y1", "y2", "y3"), rep, 10))) 
ggplot(out, aes(x, y)) + geom_line()+ facet_wrap(~gp, scales="free_y", nrow=3) 

enter image description here

相關問題