首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在同一窗口中绘制一个或多个图

在同一窗口中绘制一个或多个图
EN

Stack Overflow用户
提问于 2010-12-15 06:01:25
回答 6查看 5.3K关注 0票数 4

我想要比较两条曲线,可以用R画一张图,然后在上面画另一张图?怎么做到的?

谢谢。

EN

回答 6

Stack Overflow用户

发布于 2010-12-15 06:07:34

使用基数R,您可以绘制一条曲线,然后使用lines()参数添加第二条曲线。下面是一个简单的例子:

代码语言:javascript
复制
x <- 1:10
y <- x^2
y2 <- x^3

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

或者,如果您想使用ggplot2,这里有两种方法-一种在同一绘图上绘制不同的颜色,另一种为每个变量生成单独的绘图。这里的诀窍是首先将数据“熔化”为长格式。

代码语言:javascript
复制
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)
票数 5
EN

Stack Overflow用户

发布于 2010-12-15 16:41:34

使用lattice package

代码语言:javascript
复制
require(lattice)
x <- seq(-3,3,length.out=101)
xyplot(dnorm(x) + sin(x) + cos(x) ~ x, type = "l") 

票数 4
EN

Stack Overflow用户

发布于 2010-12-15 19:35:51

已经为您提供了一些解决方案。如果你继续使用基础包,你应该熟悉plot(), lines(), abline(), points(), polygon(), segments(), rect(), box(), arrows(), ...的函数,看看他们的帮助文件。

您应该会看到基本包中的一个绘图,它是一个窗格,其中包含您给出的坐标。在该窗格上,您可以使用上述函数绘制一整套对象。它们允许你按照你想要的方式构建图形。您应该记住,除非您使用Dr. G所示的par设置,否则每次调用plot()都会给您一个新的窗格。还要考虑到事情可以被绘制在其他事情上,所以考虑一下你用来绘制事情的顺序。

参见例如:

代码语言:javascript
复制
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")

这为您提供了:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4444727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档