R语言 在同一图中绘制多个时间序列

R语言 在同一图中绘制多个时间序列

R编程语言中的时间序列是用来观察一个对象在一段时间内的表现的。在R语言中,可以通过 ts() 函数和一些参数轻松完成。时间序列采用数据向量,每个数据都与用户给定的时间戳值相连。

方法1:使用基本的R方法

首先,我们创建一个数据向量,其中有所有需要绘制的时间序列的数据。然后,我们使用第一个数据集和plot()函数绘制时间序列。然后使用line()函数将其他时间序列添加到现有的绘图中。然后,我们可以在上面添加一个图例,以显示图中的哪条线代表哪个时间序列。

例子

# Create sample data
set.seed(1023)                          
 
sample_data <- round(data.frame(year = 1997:2021,
                     time_data1 = 1:25 + rnorm(25),
                     time_data2  = 30:6 + runif(25, 0, 10),
                     time_data3  = rnorm(25, 5, 5)))
 
# Plot a graph with time_data1
plot(sample_datayear,                          
     sample_datatime_data1,
     type = "l",
     col = 2,
     ylim = c(- 15, 40),
     xlab = "Year",
     ylab = "Values")
 
# Add line graphs of other two dataset
lines(sample_datayear,                            
      sample_datatime_data2,
      type = "l",
      col = 3)
 
lines(sample_datayear,                            
      sample_datatime_data3,
      type = "l",
      col = 4)
 
# Add legend in top right corner
legend("topright",                          
       c("Geeksforgeeks", "technical-scripter", "geek-i-knack"),
       lty = 1,
       col = 2:4)

输出

在R语言中的同一图中绘制多个时间序列

多个时间序列在一个图中

方法2:使用ggplot2

在ggplot2中,我们可以直接使用geom_line()来绘制图表。

我们首先创建一个样本数据向量。ggplot2将被用来画图,reshape将把数据从宽格式融化为长格式。将数据从宽格式转换为长格式。

语法

melt(sample_data, id.vars = variable)

在ggplot2和geom_line()的帮助下画图。

例子

# Create sample data
set.seed(1023)                          
 
sample_data <- round(data.frame(year = 1997:2021,
                     time_data1 = 1:25 + rnorm(25),
                     time_data2  = 30:6 + runif(25, 0, 10),
                     time_data3  = rnorm(25, 5, 5)))
 
# Load packages reshape2 and ggplot2
library("reshape2") 
library("ggplot2")  
 
# Convert sample_data from wide form to long form
data_final <- melt(sample_data, id.vars = "year")
 
# Plot the final data
ggplot(data_final,                           
       aes(x = year,
           y = value,
           col = variable)) + geom_line()

输出

在R语言中的同一图中绘制多个时间序列

使用ggplot2的多个时间序列

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程