Skip to main content
 首页 » 编程设计

Python Seaborn画时间序列图示例

2022年07月19日159kenshinobiy

时间序列图用于展示随着时间变化的数据值。本文介绍如何适用seaborn画各类时间序列图。

单个时间序列图

下面示例展示如何画单个时间序列图:

import pandas as pd 
import matplotlib.pyplot as plt 
import seaborn as sns  
 
df = pd.DataFrame({
   'date': ['1/2/2021', 
                            '1/3/2021', 
                            '1/4/2021', 
                            '1/5/2021', 
                            '1/6/2021', 
                            '1/7/2021', 
                            '1/8/2021'], 
                   'value': [4, 7, 8, 13, 17, 15, 21]}) 
 
sns.lineplot(x='date', y='value', data=df) 

在这里插入图片描述

当然我们可以自定义颜色、线宽、线样式、标签和标题:

sns.lineplot(x='date',y='value',data=df, linewidth=1, color='purple').set(title='Time Series Plot') 
# 设置x轴文字倾斜 
plt.xticks(rotation=15) 

在这里插入图片描述

画多组时间序列图

下面代码显示如何画多组时间序列图:

#create DataFrame 
df = pd.DataFrame({
   'date': ['1/1/2021', 
                            '1/2/2021', 
                            '1/3/2021', 
                            '1/4/2021', 
                            '1/1/2021', 
                            '1/2/2021', 
                            '1/3/2021', 
                            '1/4/2021'], 
                   'sales': [4, 7, 8, 13, 17, 15, 21, 28], 
                   'company': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B']}) 
 
#plot multiple time series 
sns.lineplot(x='date', y='sales', hue='company', data=df) 
plt.legend(loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0) 
 

在这里插入图片描述

hue 参数用于给图中每条线提供不同颜色。

bbox_to_anchor函数用来控制、调整图例框的位置。plt.legend()中的bbox_to_anchor = (x,y,width,height)中四个参数解释如下:

  • x,y表示图例框的某个点的坐标位置,具体那个点由plt.legend中的参数loc决定,例如:loc = 'center’则x,y表示图例框中心点的位置。

  • width表示将由x,y表示的原图例框的初始位置水平移动多少距离(距离原图例框的宽度);

  • height表示将由x,y表示的原图例框的初始位置竖直移动多少距离(距离原图例框的高度);


本文参考链接:https://blog.csdn.net/neweastsun/article/details/125711340