我想把y和y画在同一个图上。

x  <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
plot(x, y1, type = "l", col = "red")
plot(x, y2, type = "l", col = "green")

但当我这样画的时候,它们就不在同一个图上了。

在Matlab中是可以的,但有人知道在R中怎么做吗?


当前回答

Lines()或points()将添加到现有的图形中,但不会创建新的窗口。所以你需要这么做

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

其他回答

如果你想把图分成两列(2个相邻的图),你可以这样做:

par(mfrow=c(1,2))

plot(x)

plot(y) 

参考链接

正如@redmode所描述的,您可以使用ggplot在同一个图形设备中绘制这两条线。在这个回答中,数据是“宽”格式的。但是,在使用ggplot时,以“长”格式将数据保存在数据帧中通常是最方便的。然后,通过在美学参数中使用不同的“分组变量”,线的属性,如线类型或颜色,将根据分组变量而变化,并将出现相应的图例。

在这种情况下,我们可以使用颜色美学,它将线条的颜色匹配到数据集中变量的不同级别(这里:y1 vs y2)。但首先,我们需要将数据从宽格式融化为长格式,例如使用函数'melt'从重塑2包。这里描述了重塑数据的其他方法:将data.frame从宽格式重塑为长格式。

library(ggplot2)
library(reshape2)

# original data in a 'wide' format
x  <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
df <- data.frame(x, y1, y2)

# melt the data to a long format
df2 <- melt(data = df, id.vars = "x")

# plot, using the aesthetics argument 'colour'
ggplot(data = df2, aes(x = x, y = value, colour = variable)) + geom_line()

我们也可以使用格库

library(lattice)
x <- seq(-2,2,0.05)
y1 <- pnorm(x)
y2 <- pnorm(x,1,1)
xyplot(y1 + y2 ~ x, ylab = "y1 and y2", type = "l", auto.key = list(points = FALSE,lines = TRUE))

对于特定的颜色

xyplot(y1 + y2 ~ x,ylab = "y1 and y2", type = "l", auto.key = list(points = F,lines = T), par.settings = list(superpose.line = list(col = c("red","green"))))

与其将要绘制的值保存在数组中,不如将它们存储在矩阵中。默认情况下,整个矩阵将被视为一个数据集。然而,如果你在图中添加相同数量的修饰符,例如col(),就像你在矩阵中有行一样,R会发现每一行都应该被独立对待。例如:

x = matrix( c(21,50,80,41), nrow=2 )
y = matrix( c(1,2,1,2), nrow=2 )
plot(x, y, col("red","blue")

这应该可以工作,除非您的数据集大小不同。

您可以使用plotly包中的ggplotly()函数将这里的任何gggplot2示例转换为交互式图形,但我认为这种类型的图形没有ggplot2会更好:

# call Plotly and enter username and key
library(plotly)
x  <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)

plot_ly(x = x) %>%
  add_lines(y = y1, color = I("red"), name = "Red") %>%
  add_lines(y = y2, color = I("green"), name = "Green")