R 简明教程
R - Line Graphs
折线图是一种通过在点之间绘制线段来连接一系列点的图形。这些点按其一个坐标值(通常是 x 坐标)排序。折线图通常用于识别数据中的趋势。
A line chart is a graph that connects a series of points by drawing line segments between them. These points are ordered in one of their coordinate (usually the x-coordinate) value. Line charts are usually used in identifying the trends in data.
R 中的 plot() 函数用于创建折线图。
The plot() function in R is used to create the line graph.
Syntax
在 R 中创建折线图的基本语法为:
The basic syntax to create a line chart in R is −
plot(v,type,col,xlab,ylab)
以下是所用参数的描述 -
Following is the description of the parameters used −
-
v is a vector containing the numeric values.
-
type takes the value "p" to draw only the points, "l" to draw only the lines and "o" to draw both points and lines.
-
xlab is the label for x axis.
-
ylab is the label for y axis.
-
main is the Title of the chart.
-
col is used to give colors to both the points and lines.
Example
使用输入向量和类型参数“O”创建简单的折线图。以下脚本将在当前 R 工作目录中创建和保存折线图。
A simple line chart is created using the input vector and the type parameter as "O". The below script will create and save a line chart in the current R working directory.
# Create the data for the chart.
v <- c(7,12,28,3,41)
# Give the chart file a name.
png(file = "line_chart.jpg")
# Plot the bar chart.
plot(v,type = "o")
# Save the file.
dev.off()
当我们执行上述代码时,会产生以下结果 -
When we execute the above code, it produces the following result −

Line Chart Title, Color and Labels
可以通过使用其他参数来扩展折线图的功能。我们给点和线添加颜色,给图表添加标题并给轴添加标签。
The features of the line chart can be expanded by using additional parameters. We add color to the points and lines, give a title to the chart and add labels to the axes.
Example
# Create the data for the chart.
v <- c(7,12,28,3,41)
# Give the chart file a name.
png(file = "line_chart_label_colored.jpg")
# Plot the bar chart.
plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall",
main = "Rain fall chart")
# Save the file.
dev.off()
当我们执行上述代码时,会产生以下结果 -
When we execute the above code, it produces the following result −

Multiple Lines in a Line Chart
可以在同一张图表上绘制多条线,方法是使用 lines() 函数。
More than one line can be drawn on the same chart by using the *lines()*function.
在绘制完第一条线后,lines() 函数可以使用一个额外的向量作为输入,在图表中绘制第二条线。
After the first line is plotted, the lines() function can use an additional vector as input to draw the second line in the chart,
# Create the data for the chart.
v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)
# Give the chart file a name.
png(file = "line_chart_2_lines.jpg")
# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall",
main = "Rain fall chart")
lines(t, type = "o", col = "blue")
# Save the file.
dev.off()
当我们执行上述代码时,会产生以下结果 -
When we execute the above code, it produces the following result −
