R中多个变量的线图

Man*_*ish 5 graphics r line-plot

我输入的数据格式如下.

  x      y       z
  0      2.2     4.5
  5      3.8     6.8
  10     4.6     9.3
  15     7.6     10.5
Run Code Online (Sandbox Code Playgroud)

如何在R中绘制像excel(如下所示)的xy散点图?

在此输入图像描述

mar*_*bel 11

至少有四种方法:

1)在这里使用名为df的"水平"或"宽"data.frame

df <- data.frame(x = c(0, 5, 10, 15), y = c(2.2, 3.8, 4.6, 7.6), z = c(4.5, 6.8, 9.3, 10.5))
ggplot(df, aes(x)) + 
  geom_line(aes(y = y, colour = "y")) + 
  geom_line(aes(y = z, colour = "z"))
Run Code Online (Sandbox Code Playgroud)

2)使用格子

require(lattice)
xyplot(x ~ y + z, data=df, type = c('l','l'), col = c("blue", "red"), auto.key=T)
Run Code Online (Sandbox Code Playgroud)

3)将原始df转换为"长"data.frame.这就是你通常如何处理数据的方式ggplot2

require("reshape")
require("ggplot2")

mdf <- melt(df, id="x")  # convert to long format
ggplot(mdf, aes(x=x, y=value, colour=variable)) +
    geom_line() + 
    theme_bw()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

4)使用matplot()我没有真正探索过这个选项,但这是一个例子.

matplot(df$x, df[,2:3], type = "b", pch=19 ,col = 1:2)
Run Code Online (Sandbox Code Playgroud)


gun*_*ica 6

如果你能说出你在这里停留的东西可能会有所帮助.这个真的很琐碎R.你应该查找的文档?情节,和?行.对于简单的概述,Quick R很棒.这是代码:

windows()
  plot(x, y, type="l", lwd=2, col="blue", ylim=c(0, 12), xaxs="i", yaxs="i")
  lines(x,z, lwd=2, col="red")
  legend("topleft", legend=c("y","z"), lwd=c(2,2), col=c("blue","red"))
Run Code Online (Sandbox Code Playgroud)

请注意,如果您使用的是Mac,则需要quartz()代替windows().这是情节:

在此输入图像描述