2010-12-14 200 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

相关问题