📜  如何在 Matplotlib 中绘制时间序列?

📅  最后修改于: 2022-05-13 01:54:52.496000             🧑  作者: Mango

如何在 Matplotlib 中绘制时间序列?

时间序列数据是一些时间标记的数据。图表上的每个点都代表时间和数量的度量。当数据按时间顺序由一条形成连续波峰和波谷的直线连接时,时间序列图也称为发热图。图表的 x 轴用于表示时间间隔。 y 线定位被监控参数的值。

我们将使用下面提到的语法来绘制时间序列图:

句法:

plt.plot(dataframe.X, dataframe.Y)

在哪里

  • X 变量属于日期时间。给定数据框中的 datetime() 类。
  • Y变量属于日期对应的值

我们也可以使用 xticks()函数来旋转轴

语法

plt.xticks(rotation, ha)

在哪里

  • 旋转描述您要旋转的度数
  • ha 描述位置,如右、左、上、下

方法

  • 我们的图形需要有两个轴,即 X 轴和 Y 轴。我们将首先使用一个数据框来绘制图表。
  • 我们既可以制作自己的数据框,也可以使用一些公开可用的数据框。在 X 轴上,我们应该有一个 DateTime 变量。在 Y 轴上,我们可以有我们想要分析的关于时间的变量。
  • plt.plot() 方法用于在 matplotlib 中绘制图形。
  • 为了提供标签和标题以使我们的图形有意义,我们可以使用诸如 plt.title()、plt.xlabel()、plt.ylabel() 之类的方法

示例 1:

假设我们有一个星期几的数据框和下一周每一天的课程数量。从 2021 年 1 月 11 日到 2021 年 7 月 11 日,我们需要 7 天

Python3
# import modules
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import numpy as np
 
# create dataframe
 
dataframe = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)
                                                    for i in range(7)]),
                          'classes': [5, 6, 8, 2, 3, 7, 4]})
 
# Plotting the time series of given dataframe
plt.plot(dataframe.date_of_week, dataframe.classes)
 
# Giving title to the chart using plt.title
plt.title('Classes by Date')
 
# rotating the x-axis tick labels at 30degree
# towards right
plt.xticks(rotation=30, ha='right')
 
# Providing x and y label to the chart
plt.xlabel('Date')
plt.ylabel('Classes')


Python3
#import modules
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import numpy as np
 
# Let say we have a dataframe of the days of
# the week and number of classes in each day of the upcoming week.
# Taking 7 days from 1-11-2021 to 7-11-2021
 
dataframe = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)
                                                    for i in range(7)]),
                          'classes': [5, 6, 8, 2, 3, 7, 4]})
 
# To draw scatter time series plot of the given dataframe
plt.plot_date(dataframe.date_of_week, dataframe.classes)
 
# rotating the x-axis tick labels at 30degree towards right
plt.xticks(rotation=30, ha='right')
 
# Giving title to the chart using plt.title
plt.title('Classes by Date')
 
# Providing x and y label to the chart
plt.xlabel('Date')
plt.ylabel('Classes')


Python3
# Initialising required libraries
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import numpy as np
 
# ABC colllege classes by date- from 01-11-2021 to 07-11-2021
abc = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)
                                              for i in range(7)]),
                    'classes': [5, 6, 8, 2, 3, 7, 4]})
 
 
# XYZ colllege classes by date - from 01-11-2021 to 07-11-2021
xyz = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)
                                              for i in range(7)]),
                    'classes': [2, 3, 7, 3, 4, 1, 2]})
 
# plotting the time series of ABC college dataframe
plt.plot(abc.date_of_week, abc.classes)
 
# plotting the time series of XYZ college dataframe
plt.plot(xyz.date_of_week, xyz.classes, color='green')
 
# Giving title to the graph
plt.title('Classes by Date')
 
# rotating the x-axis tick labels at 30degree
# towards right
plt.xticks(rotation=30, ha='right')
 
# Giving x and y label to the graph
plt.xlabel('Date')
plt.ylabel('Classes')


Python3
# Initialising required libraries
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import numpy as np
 
# Loading the dataset
data = pd.read_csv("C:/Users/aparn/Desktop/data.csv")
 
# X axis is price_date
price_date = data['Date']
 
# Y axis is price closing
price_close = data['Close']
 
# Plotting the timeseries graph of given dataset
plt.plot(price_date, price_close)
 
# Giving title to the graph
plt.title('Prices by Date')
 
# rotating the x-axis tick labels at 30degree
# towards right
plt.xticks(rotation=30, ha='right')
 
# Giving x and y label to the graph
plt.xlabel('Price Date')
plt.ylabel('Price Close')


输出

我们还可以借助 matplotlib 借助时间序列创建散点图。

示例 2:给定数据帧的 Scatter 时间序列图

Python3

#import modules
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import numpy as np
 
# Let say we have a dataframe of the days of
# the week and number of classes in each day of the upcoming week.
# Taking 7 days from 1-11-2021 to 7-11-2021
 
dataframe = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)
                                                    for i in range(7)]),
                          'classes': [5, 6, 8, 2, 3, 7, 4]})
 
# To draw scatter time series plot of the given dataframe
plt.plot_date(dataframe.date_of_week, dataframe.classes)
 
# rotating the x-axis tick labels at 30degree towards right
plt.xticks(rotation=30, ha='right')
 
# Giving title to the chart using plt.title
plt.title('Classes by Date')
 
# Providing x and y label to the chart
plt.xlabel('Date')
plt.ylabel('Classes')

输出

同样,我们可以绘制两个数据帧的时间序列并进行比较。假设我们有两所大学——“XYZ”和“ABC”。现在我们需要通过 matplotlib 的时间序列图来比较这两者。

示例 3:

Python3

# Initialising required libraries
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import numpy as np
 
# ABC colllege classes by date- from 01-11-2021 to 07-11-2021
abc = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)
                                              for i in range(7)]),
                    'classes': [5, 6, 8, 2, 3, 7, 4]})
 
 
# XYZ colllege classes by date - from 01-11-2021 to 07-11-2021
xyz = pd.DataFrame({'date_of_week': np.array([datetime.datetime(2021, 11, i+1)
                                              for i in range(7)]),
                    'classes': [2, 3, 7, 3, 4, 1, 2]})
 
# plotting the time series of ABC college dataframe
plt.plot(abc.date_of_week, abc.classes)
 
# plotting the time series of XYZ college dataframe
plt.plot(xyz.date_of_week, xyz.classes, color='green')
 
# Giving title to the graph
plt.title('Classes by Date')
 
# rotating the x-axis tick labels at 30degree
# towards right
plt.xticks(rotation=30, ha='right')
 
# Giving x and y label to the graph
plt.xlabel('Date')
plt.ylabel('Classes')

输出:

同样,我们可以从数据集中绘制时间序列图。这是数据集的链接

示例 4:

Python3

# Initialising required libraries
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import numpy as np
 
# Loading the dataset
data = pd.read_csv("C:/Users/aparn/Desktop/data.csv")
 
# X axis is price_date
price_date = data['Date']
 
# Y axis is price closing
price_close = data['Close']
 
# Plotting the timeseries graph of given dataset
plt.plot(price_date, price_close)
 
# Giving title to the graph
plt.title('Prices by Date')
 
# rotating the x-axis tick labels at 30degree
# towards right
plt.xticks(rotation=30, ha='right')
 
# Giving x and y label to the graph
plt.xlabel('Price Date')
plt.ylabel('Price Close')

输出: