使用R在一个图上绘制多个线段

时间:2012-02-01 15:08:51

标签: r plot ggplot2

如何复制这种图形样式,在一个图表上有多个图表,最好是附图如下所示。

我尝试了“facet”的概念,但是ggplot2和trellis:xyplot都将facet视为单独的面板而不是重叠的图。

我可以使用普通的Jane plot()和line()..但是使用ggplot2和woudl喜欢在该包中的一个图上获得多行。

以下是一些长形式的示例数据(使用名为“Graphclick”的漂亮应用从图中捕获)

comp <- read.table(pipe("pbpaste"), header=T, sep=',')

company, year, sales
Apple,1975.003,17298.457
Apple,1977.302,16784.502
Apple,1978.314,17298.457
Apple,1980.246,20730.098
Apple,1981.533,27608.426
Apple,1984.293,40862.852
Apple,1986.408,50468.617
Apple,1987.328,48236.188
Apple,1988.892,35676.547
Apple,1989.904,34616.582
Apple,1991.192,44732.742
Apple,1992.387,44732.742
Apple,1993.399,39055.324
Apple,1995.791,37894.922
Apple,1996.895,39648.746
Apple,1998.274,52804.367
Apple,1999.378,61399.512
Apple,2001.770,2.350e5
Apple,2005.265,7.735e5
Toshiba,1999.378,86856.6
Toshiba,2001.862,1.192e5
Toshiba,2004.069,1.495e5
Toshiba,2004.069,1.495e5
IBM,1975.003,22019.092
IBM,1975.830,27195.193
IBM,1976.934,30682.320
IBM,1978.130,31148.527
IBM,1980.430,35676.547
IBM,1981.625,35676.547
IBM,1983.005,39648.746
IBM,1985.305,40862.852
IBM,1986.408,46102.508
IBM,1987.512,64241.156
IBM,1989.996,75832.898
IBM,1991.100,84276.039
IBM,1992.295,85556.641
IBM,1993.307,79342.539
IBM,1994.779,79342.539
IBM,1995.791,84276.039
IBM,1996.895,95082.484
IBM,1996.895,95082.484
Commodore,1975.003,33588.051
Commodore,1975.830,34616.582
Commodore,1977.118,25219.982
Commodore,1978.130,23388.229
Commodore,1979.326,25992.234
Commodore,1980.521,21689.514
Commodore,1981.717,25219.982
Commodore,1984.201,6999.029
Commodore,1985.213,1670.460
Commodore,1986.408,1458.447

computing over time http://www.asymco.com/wp-content/uploads/2012/01/Screen-Shot-2012-01-18-at-1-18-4.31.31-PM.png

2 个答案:

答案 0 :(得分:5)

如果您正在寻找最多的控件,您可以使用低级绘图和线命令。使用“plot”生成第一个图形(带有标题,xlimits和ylimits),然后使用“lines”为该图形添加线条。

plot(0,type="n", xlim=c(0,10), ylim=c(0,10), xlab="X Label", ylab="Y Label", main="Title")

然后使用lines命令添加行:

lines(1:10, 1:10, type="l", lty=2)
lines(2:4, 10:8, col=2, type="l")
lines(6:9, c(5,6,5,6), col=3, type="l")

您可以使用“par”帮助文件中列出的所有参数(“?par”)来微调外观

Output of commands

答案 1 :(得分:5)

所以,在ggplot2中,这段代码可以正常工作

qplot(year, sales, data=comp, colour=as.factor(company), group= company, geom="path", log="y")

现在唯一剩下的就是将Y轴上的值格式化为数字(不是sci表示法),标签位于图表外的图例中,而不是图表上......欢迎提出最终建议。

这比plot()+ lines()更容易,因为它需要支持代码来获取范围,迭代组级别等。

image