Line plot of multiple variables in R

感情迁移 提交于 2019-12-04 23:50:34

问题


I have input data in below format.

  x      y       z
  0      2.2     4.5
  5      3.8     6.8
  10     4.6     9.3
  15     7.6     10.5

How can i plot the xy scatter plot like excel (show below) in R?


回答1:


There at least four ways of doing this:

1) Use a "horizontal" or "wide" data.frame called df here

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

2) Using lattice

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

3) Turn your original df into a "long" data.frame. This is how it's usually how you would work with data in 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()

4) Using matplot() I haven't really explored much this option but here is an example.

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



回答2:


It might help if you could say what you're stuck on here. This is really quite trivial in R. You should look up the documentation for ?plot, and ?lines. For a simple overview, Quick R is great. Here's the code:

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

Note that if you use a Mac, you need quartz() instead of windows(). Here's the plot:



来源:https://stackoverflow.com/questions/17562379/line-plot-of-multiple-variables-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!