R语言线形图

线形图是通过在多个点之间绘制线段来连接一系列点所形成的图形。这些点按其坐标(通常是x坐标)的值排序。线形图通常用于识别数据趋势。

R中的通过使用plot()函数来创建线形图。

语法

在R中创建线形图的基本语法是 –

plot(v,type,col,xlab,ylab)

以下是使用的参数的描述 –

  • v – 是包含数值的向量。
  • type – 取值“p”表示仅绘制点,“l”表示仅绘制线条,“o”表示仅绘制点和线。
  • xlab – 是x轴的标签。
  • ylab – 是y轴的标签。
  • main – 是图表的标题。
  • col – 用于绘制点和线两种颜色。

例子

使用输入向量和类型参数为“O”创建一个简单的折线图。以下脚本将在当前R工作目录中创建并保存折线图。

setwd("F:/worksp/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", main = "降雨量图表")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 –

线图标题,颜色和标签

可以通过使用附加参数来扩展折线图的功能。如如可以向点和线添加颜色,给图表标题,并在轴上添加标签。参考以下示例代码 –

setwd("F:/worksp/R")
# 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 = "月份", ylab = "降雨量",
   main = "降雨量图表")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 –

《R语言线形图》

多线条图表

可以使用lines()函数在同一个图表上绘制多个直接。

在绘制第一行之后,lines()函数可以使用附加向量作为输入来绘制图表中的第二行,参考以下代码 –

setwd("F:/worksp/R")
# 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 = "月份", ylab = "降雨量", 
   main = "降雨量图表")

lines(t, type = "o", col = "blue")

# Save the file.
dev.off()

当我们执行上述代码时,会产生以下结果 –

《R语言线形图》

        原文作者:R语言教程
        原文地址: https://www.yiibai.com/r/r_line_graphs.html
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
    点赞