首页 文章

绘制不同层中的线 - ggplot2

提问于
浏览
1

我有三个看起来与这些相似的向量,在R中,我想在同一个图上绘制它们

a <- c(3, 6, 16, 17, 11, 21)
b <- c(0.3, 2.3, 9, 9, 5 ,12)
c <- c(3, 7, 9, 7, 6, 10)

有谁知道我可以使用ggplot2包编写以下命令吗?

colours <- rainbow(3)
plot(a, col=colours[1], type="l", ylim=c(min(m), max(m)),
     xlab="time[h]", main="bla")
lines(b, col=colours[2])
lines(c, col=colours[3])
legend(x="bottomright", legend=c("a","b", "c"),
       col=c(colours[1],colours[2],colours[3]), pch=19, inset=0.01)

我只是设法绘制单独的线条或使用切面绘制它们 - 通过从矢量创建数据框 .

干杯!

2 回答

  • 2

    是的,我们这样做 .

    首先,将数据放在数据框中,然后使用 melt 将其转换为'long'格式:

    dat <- data.frame(a=a,b=b,c=c)
    dat <- melt(dat)
    

    接下来,我们在数据框中添加一个显式的'x'变量:

    dat$x <- rep(1:6,times=3)
    

    最后,我们可以使用以下代码绘制图形:

    ggplot(dat,aes(x=x,y=value)) + 
        geom_line(aes(colour=variable)) + 
        scale_colour_manual(values=colours) + 
        labs(x="time[h]",y="a",colour="") + 
        opts(title="bla")
    
  • 0

    像这样的东西?

    a<-c(3,6,16,17,11,21) 
    b<-c(0.3, 2.3, 9, 9, 5 ,12) 
    c<-c(3, 7,9, 7, 6 ,10)
    x <- 1:6
    
    df <- data.frame(a,b,c,x)
    require(reshape)
    dfm <- melt(df, id = "x")
    
    require(ggplot2)
    ggplot(dfm, aes(x = x, y = value, col = variable)) + 
      geom_line() + 
      theme_bw() +
      opts(panel.grid.major = theme_blank(),
        panel.grid.minor = theme_blank(),
        legend.position = c(.9, .2),
        title = "bla") +
      ylab("a") +
      xlab("time [h]") +
      scale_color_discrete("")
    

相关问题