2010-12-14 208 views
4

我想比較兩條曲線,可以用R繪製一個繪圖,然後繪製另一個繪圖?怎麼樣 ?在同一個窗口中繪製一個或多個繪圖

謝謝。

+1

如果你想要更多的例子,你應該看一看在r圖形庫(http://addictedtor.free.fr/graphiques/)這是一個很好的來源作爲代碼的靈感和結果在那裏。 – 2010-12-16 19:52:46

回答

1

看一看面值

> ?par 
> plot(rnorm(100)) 
> par(new=T) 
> plot(rnorm(100), col="red") 
5

隨着基礎R,你可以畫出你的一個曲線,然後用lines()參數添加第二條曲線。這裏有一個簡單的例子:

x <- 1:10 
y <- x^2 
y2 <- x^3 

plot(x,y, type = "l") 
lines(x, y2, col = "red") 

另外,如果你想使用GGPLOT2,這裏有兩種方法 - 在同一個情節情節不同的顏色,以及其他產生不同的地塊爲每個變量。這裏的技巧是首先將數據「融化」爲長格式。

library(ggplot2) 

df <- data.frame(x, y, y2) 

df.m <- melt(df, id.var = "x") 

qplot(x, value, data = df.m, colour = variable, geom = "line") 

qplot(x, value, data = df.m, geom = "line")+ facet_wrap(~ variable) 
0

用matplot函數同時繪製多條曲線。幫助(matplot)獲得更多。

4

使用lattice package

require(lattice) 
x <- seq(-3,3,length.out=101) 
xyplot(dnorm(x) + sin(x) + cos(x) ~ x, type = "l") 

Lattice curve plot

+0

+1使用格子 – 2010-12-15 11:36:33

2

還有的是一些解決方案已經爲你。如果你使用基礎包,你應該熟悉這些功能plot(), lines(), abline(), points(), polygon(), segments(), rect(), box(), arrows(), ...看看他們的幫助文件。

您應該從基本包中看到一個繪圖,並將其作爲一個窗格,並顯示您給出的座標。在該窗格上,可以繪製具有上述功能的一整套對象。它們允許您根據需要構建圖形。儘管如此,除非您使用Dr. G展示的參數設置進行遊戲,否則每次調用plot()都會爲您提供一個新窗格。還要考慮到事物可能會被其他事物陰謀詭計,所以想想你用來繪製事物的順序。

見如:

set.seed(100) 
x <- 1:10 
y <- x^2 
y2 <- x^3 
yse <- abs(runif(10,2,4)) 

plot(x,y, type = "n") # type="n" only plots the pane, no curves or points. 

# plots the area between both curves 
polygon(c(x,sort(x,decreasing=T)),c(y,sort(y2,decreasing=T)),col="grey") 
# plot both curves 
lines(x,y,col="purple") 
lines(x, y2, col = "red") 
# add the points to the first curve 
points(x, y, col = "black") 
# adds some lines indicating the standard error 
segments(x,y,x,y+yse,col="blue") 
# adds some flags indicating the standard error 
arrows(x,y,x,y-yse,angle=90,length=0.1,col="darkgreen") 

這給了你:

alt text

1

GGPLOT2是這樣的事情一個很大的包:

install.packages('ggplot2') 
require(ggplot2) 
x <- 1:10 
y1 <- x^2 
y2 <- x^3 
df <- data.frame(x = x, curve1 = y1, curve2 = y2) 
df.m <- melt(df, id.vars = 'x', variable_name = 'curve') 
# now df.m is a data frame with columns 'x', 'curve', 'value' 
ggplot(df.m, aes(x,value)) + geom_line(aes(colour = curve)) + 
geom_point(aes(shape=curve)) 

你得到的情節有色通過曲線以及每條曲線的不同piont標記,以及一個不錯的傳說,所有無痛,沒有任何額外的工作:

alt text

+0

你的代碼不會以當前的形式運行。在初始調用'ggplot'之後,你錯過了一個parens並引用了錯誤的對象。這是一個工作版本:' ggplot(df.m,aes(x,value))+ geom_line(aes(color = curve))+ geom_point(aes(shape = curve))' – Chase 2010-12-16 00:04:15

+0

謝謝Chase, sl。。 – 2010-12-16 18:20:13

相關問題