【发布时间】:2010-12-14 22:01:24
【问题描述】:
我想比较两条曲线,可以用 R 画一个图,然后在上面画另一个图吗?怎么样?
谢谢。
【问题讨论】:
-
如果您想要更多示例,您应该查看 R 图形库 (addictedtor.free.fr/graphiques),它是一个很好的灵感来源,因为代码和结果都在那里。
我想比较两条曲线,可以用 R 画一个图,然后在上面画另一个图吗?怎么样?
谢谢。
【问题讨论】:
使用底数 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)
【讨论】:
require(lattice)
x <- seq(-3,3,length.out=101)
xyplot(dnorm(x) + sin(x) + cos(x) ~ x, type = "l")
【讨论】:
已经为您提供了一些解决方案。如果你使用基本包,你应该熟悉函数plot(), lines(), abline(), points(), polygon(), segments(), rect(), box(), arrows(), ...看看他们的帮助文件。
您应该会从基本包中看到一个带有您给它的坐标的窗格。在该窗格中,您可以使用上述功能绘制一整套对象。它们允许您根据需要构建图表。不过你应该记住,除非你像 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")
这给了你:
【讨论】:
看看标准
> ?par
> plot(rnorm(100))
> par(new=T)
> plot(rnorm(100), col="red")
【讨论】:
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))
你会得到曲线着色的图,每条曲线都有不同的点标记,还有一个漂亮的图例,所有这些都毫不费力,无需任何额外的工作:
【讨论】:
ggplot 后,您缺少一个括号,并且引用了错误的对象。这是一个工作版本:` ggplot(df.m, aes(x,value)) + geom_line(aes(colour = curve)) + geom_point(aes(shape=curve))'
使用matplot函数同时绘制多条曲线。做更多的帮助(matplot)。
【讨论】: