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


当前回答

您还可以在同一图形但不同的轴上使用par和plot。具体如下:

plot( x, y1, type="l", col="red" )
par(new=TRUE)
plot( x, y2, type="l", col="green" )

如果你详细阅读了R中的par,你将能够生成真正有趣的图形。另一本书是Paul Murrel的《R Graphics》。

其他回答

你也可以使用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')

这将创建以下情节:

使用plotly(用主要和次要y轴从plotly中添加溶液-它似乎缺失了):

library(plotly)     
x  <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)

df=cbind.data.frame(x,y1,y2)

  plot_ly(df) %>%
    add_trace(x=~x,y=~y1,name = 'Line 1',type = 'scatter',mode = 'lines+markers',connectgaps = TRUE) %>%
    add_trace(x=~x,y=~y2,name = 'Line 2',type = 'scatter',mode = 'lines+markers',connectgaps = TRUE,yaxis = "y2") %>%
    layout(title = 'Title',
       xaxis = list(title = "X-axis title"),
       yaxis2 = list(side = 'right', overlaying = "y", title = 'secondary y axis', showgrid = FALSE, zeroline = FALSE))

工作演示截图:

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。

您还可以在同一图形但不同的轴上使用par和plot。具体如下:

plot( x, y1, type="l", col="red" )
par(new=TRUE)
plot( x, y2, type="l", col="green" )

如果你详细阅读了R中的par,你将能够生成真正有趣的图形。另一本书是Paul Murrel的《R Graphics》。

正如@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()