概观
折线图用函数行(x ,y ,type =)创建,其中x和y是要连接的(x,y)点的数值向量。type =可以取下列值:
类型 | 描述 |
p | 点 |
升 | 线 |
Ø | overplotted点和线 |
b,c | 点(如果“c”则为空)通过线连接 |
S,S | 楼梯的步骤 |
H | 直方图像垂直线 |
ñ | 不会产生任何点或线 |
所述线()函数增加了信息的曲线图。它不能自行生成图表。通常它遵循生成图形的plot(x ,y )命令。
默认情况下,plot()绘制(x,y)点。在plot()命令中使用type =“n”选项 来创建带有坐标轴,标题等的图形,但不绘制点。
(要练习使用此行()函数创建折线图,请尝试此练习。)
例
在以下代码中,每个type =选项都应用于相同的数据集。该图()命令设置的图形,但不积点。
x <- c(1:5); y <- x # create some data
par(pch=22, col="red") # plotting symbol and color
par(mfrow=c(2,4)) # all plots on one page
opts = c("p","l","o","b","c","s","S","h")
for(i in 1:length(opts)){
heading = paste("type=",opts[i])
plot(x, y, type="n", main=heading)
lines(x, y, type=opts[i])
}
接下来,我们证明每个类型=选项时图()建立图形并确实积的点。
x <- c(1:5); y <- x # create some data
par(pch=22, col="blue") # plotting symbol and color
par(mfrow=c(2,4)) # all plots on one page
opts = c("p","l","o","b","c","s","S","h")
for(i in 1:length(opts){
heading = paste("type=",opts[i])
plot(x, y, main=heading)
lines(x, y, type=opts[i])
}
如您所见,如果plot()命令中的点的绘图被抑制,type =“c”选项仅与type =“b”选项看起来不同。
为了演示更复杂折线图的创建,让我们随时间绘制5棵橙树的增长情况。每棵树都有自己独特的线条。数据来自数据集Orange。
# Create Line Chart
# convert factor to numeric for convenience
Orange$Tree <- as.numeric(Orange$Tree)
ntrees <- max(Orange$Tree)
# get the range for the x and y axis
xrange <- range(Orange$age)
yrange <- range(Orange$circumference)
# set up the plot
plot(xrange, yrange, type="n", xlab="Age (days)",
ylab="Circumference (mm)" )
colors <- rainbow(ntrees)
linetype <- c(1:ntrees)
plotchar <- seq(18,18+ntrees,1)
# add lines
for (i in 1:ntrees) {
tree <- subset(Orange, Tree==i)
lines(tree$age, tree$circumference, type="b", lwd=1.5,
lty=linetype[i], col=colors[i], pch=plotchar[i])
}
# add a title and subtitle
title("Tree Growth", "example of line plot")
# add a legend
legend(xrange[1], yrange[2], 1:ntrees, cex=0.8, col=colors,
pch=plotchar, lty=linetype, title="Tree")