我想把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中怎么做吗?


当前回答

我们也可以使用格库

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"))))

其他回答

使用matplot函数:

matplot(x, cbind(y1,y2),type="l",col=c("red","green"),lty=c(1,1))

如果y和y在相同的x点上求值,就用这个。它缩放y轴以适应哪个更大(y1或y2),不像这里的一些其他答案,如果y2大于y1,就会剪辑y2 (ggplot解决方案大多数都可以接受这一点)。

或者,如果两条线没有相同的x坐标,在第一个图上设置轴限制,并添加:

x1  <- seq(-2, 2, 0.05)
x2  <- seq(-3, 3, 0.05)
y1 <- pnorm(x1)
y2 <- pnorm(x2,1,1)

plot(x1,y1,ylim=range(c(y1,y2)),xlim=range(c(x1,x2)), type="l",col="red")
lines(x2,y2,col="green")

我很惊讶这个Q已经4岁了,没有人提到matplot或x/ylim…

Idiomatic Matlab plot(x1,y1,x2,y2)可以用ggplot2在R中翻译,例如:

x1 <- seq(1,10,.2)
df1 <- data.frame(x=x1,y=log(x1),type="Log")
x2 <- seq(1,10)
df2 <- data.frame(x=x2,y=cumsum(1/x2),type="Harmonic")

df <- rbind(df1,df2)

library(ggplot2)
ggplot(df)+geom_line(aes(x,y,colour=type))

灵感来自赵婷婷x轴范围不同的双线图使用ggplot2。

我们也可以使用格库

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"))))

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

par(mfrow=c(1,2))

plot(x)

plot(y) 

参考链接

你也可以使用ggvis创建你的绘图:

library(ggvis)

x  <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x,1,1)
df <- data.frame(x, y1, y2)

df %>%
  ggvis(~x, ~y1, stroke := 'red') %>%
  layer_paths() %>%
  layer_paths(data = df, x = ~x, y = ~y2, stroke := 'blue')

这将创建以下情节: