首页 文章

在R中的相同图中绘制两个图

提问于
浏览
476

我想在同一个情节中绘制y1和y2 .

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中可以做 hold on ,但是有人知道如何在R中做到这一点吗?

15 回答

  • 14

    习惯用法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))
    

    enter image description here

    灵感来自婷婷赵的双线图,具有不同的x轴范围使用ggplot2 .

  • 1

    如果你想分割屏幕,你可以这样做:

    (例如,下面的2个图)

    par(mfrow=c(1,2))
    
    plot(x)
    
    plot(y)
    

    Reference Link

  • 9

    我们也可以使用格子库

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

    enter image description here

  • 4

    你可以使用点作为上图,即 .

    plot(x1, y1,col='red')
    
    points(x2,y2,col='blue')
    
  • 184

    不是将值保存在数组中,而是将它们存储在矩阵中 . 默认情况下,整个矩阵将被视为一个数据集 . 但是,如果向绘图添加相同数量的修改器,例如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")
    

    除非您的数据集具有不同的大小,否则这应该有效 .

  • 99

    tl;dr: 您想使用 curve (使用 add=TRUE )或 lines .


    我不同意 par(new=TRUE) 因为这会打印刻度线和轴标签 . 例如

    sine and parabola

    plot(sin); par(new=T); plot( function(x) x**2 ) 的输出 .

    看看垂直轴标签是多么混乱!由于范围不同,您需要设置 ylim=c(lowest point between the two functions, highest point between the two functions) ,这比我要向您展示的要简单得多 - 如果您想要添加的不仅仅是两条曲线,还有很多曲线,那就不那么容易了 .


    总是让我对绘图感到困惑的是 curvelines 之间的区别 . (如果您不记得这些是两个重要绘图命令的名称,只需sing它 . )

    这是曲线和线条之间的巨大差异 .

    curve 将绘制一个函数,如 curve(sin) . lines 用x和y值绘制点,如: lines( x=0:10, y=sin(0:10) ) .

    这里有一个小的区别: curve 需要用 add=TRUE 来调用你正在尝试做的事情,而 lines 已经假定你正在添加到现有的情节中 .

    id & sine

    这是调用 plot(0:2); curve(sin) 的结果 .


    在幕后,请查看 methods(plot) . 并检查 body( plot.function )[[5]] . 当你调用 plot(sin) 时,R指出 sin 是一个函数(不是y值)并使用 plot.function 方法,最终调用 curve . 所以 curve 是用于处理功能的工具 .

  • 7

    在构建多层图时,应考虑 ggplot 包 . 我们的想法是创建一个具有基本美学的图形对象,并逐步增强它 .

    ggplot 样式需要在 data.frame 中打包数据 .

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

    基本解决方案

    require(ggplot2)
    
    ggplot(df, aes(x)) +                    # basic graphical object
      geom_line(aes(y=y1), colour="red") +  # first layer
      geom_line(aes(y=y2), colour="green")  # second layer
    

    这里 + operator 用于向基本对象添加额外的图层 .

    使用 ggplot ,您可以在绘图的每个阶段访问图形对象 . 比方说,通常的逐步设置可能如下所示:

    g <- ggplot(df, aes(x))
    g <- g + geom_line(aes(y=y1), colour="red")
    g <- g + geom_line(aes(y=y2), colour="green")
    g
    

    g 生成绘图,您可以在每个阶段(在创建至少一个图层之后)看到它 . 绘图的进一步附魔也是用创建的对象完成的 . 例如,我们可以为轴添加标签:

    g <- g + ylab("Y") + xlab("X")
    g
    

    最终 g 看起来像:

    enter image description here

    UPDATE (2013-11-08):

    正如评论中指出的那样, ggplot 的哲学建议使用长格式的数据 . 您可以参考这个答案https://stackoverflow.com/a/19039094/1796914以查看相应的代码 .

  • 5

    使用 matplot 函数:

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

    如果 y1y2 在相同的 x 点评估,请使用此方法 . 它缩放Y轴以适合更大的那个( y1y2 ),不像其他一些答案,如果它变得大于 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岁,没人提到 matplotx/ylim ......

  • 15

    我认为你要找的答案是:

    plot(first thing to plot)
    plot(second thing to plot,add=TRUE)
    
  • 24

    您可以使用Plotly R API来设置此样式 . 下面是执行此操作的代码,此图表的实时版本为here .

    # call Plotly and enter username and key
    library(plotly)
    p <- plotly(username="Username", key="API_KEY")
    
    # enter data
    x  <- seq(-2, 2, 0.05)
    y1 <- pnorm(x)
    y2 <- pnorm(x,1,1)
    
    # format, listing y1 as your y.
    First <- list(
    x = x,
    y = y1,
    type = 'scatter',
    mode = 'lines',
    marker = list(
        color = 'rgb(0, 0, 255)',
        opacity = 0.5
     )
    )
    
    # format again, listing y2 as your y.
    Second <- list(
    x = x,
    y = y2,
    type = 'scatter',
    mode = 'lines',
    opacity = 0.8, 
    marker = list(
        color = 'rgb(255, 0, 0)'
     )
    )
    
    # style background color
    plot_bgcolor = 'rgb(245,245,247)'
    
    # and structure the response. Plotly returns a URL when you make the call. 
    response<-p$plotly(list(First,Second), kwargs = list(layout=layout))
    

    完全披露:我在Plotly团队 .

    Graph

  • 3

    lines()points() 将添加到现有图表,但不会创建新窗口 . 所以你需要这样做

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

    如果您正在使用基本图形(即非格子/网格图形),那么您可以通过使用点/线/多边形函数来模拟MATLAB的保持功能,以便在不创建新图的情况下向图中添加其他详细信息 . 在多画布布局的情况下,您可以使用 par(mfg=...) 选择要添加内容的绘图 .

  • 22

    您也可以使用 par 并绘制在同一图表上,但绘制不同的轴 . 如下:

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

    如果您在 R 中详细了解 par ,您将能够生成非常有趣的图表 . 另一本值得关注的书是Paul Murrel的R Graphics .

  • 516

    您还可以使用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')
    

    这将创建以下图:

    enter image description here

  • 15

    如@redmode所述,您可以使用 ggplot 在同一图形设备中绘制两条线 . 但是,数据在答案是'wide'格式,而在 ggplot 中,通常最方便的是将数据保存在'long'格式的数据框中 . 然后,通过在 aes thetics参数中使用不同的'grouping variables',行的属性(如线型或颜色)将根据分组变量而变化,并且将显示相应的图例 . 在这种情况下,我们可以使用 colour aes 美学,它将行的颜色与数据集中变量的不同级别(此处:y1与y2)相匹配 . 但首先我们需要使用 reshape2 函数中的'melt'函数将数据从宽格式转换为长格式 .

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

    enter image description here

相关问题