R 折线图
折线图是通过在点之间绘制线段来连接一系列点的图形。这些点按其坐标(通常是 x 坐标)值之一排序。折线图通常用于识别数据趋势。
R 中的
plot() 函数用于创建折线图。
语法
在 R 中创建折线图的基本语法是-
plot(v,type,col,xlab,ylab)
以下是所用参数的说明-
v 是包含数值的向量。
type 取值"p"只绘制点,"l"只绘制线,"o"绘制点和线。
xlab 是 x 轴的标签。
ylab 是 y 轴的标签。
main 是图表的标题。
col 用于为点和线赋予颜色。
示例
使用输入向量和类型参数作为"O"创建一个简单的折线图。以下脚本将在当前 R 工作目录中创建并保存折线图。
# 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()
当我们执行上面的代码时,它会产生以下结果-
折线图标题、颜色和标签
可以通过使用附加参数来扩展折线图的功能。我们为点和线添加颜色,为图表指定标题并为轴添加标签。
示例
# 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()
当我们执行上面的代码时,它会产生以下结果-
折线图中的多条线
使用
lines()函数可以在同一张图表上绘制多条线。
绘制第一条线后,lines() 函数可以使用额外的向量作为输入在图表中绘制第二条线,
# 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()
当我们执行上面的代码时,它会产生以下结果-