如何按年份或在同一图上显示多条线来将子图中的可视化分开?

问题描述

在问这个问题之前,我昨天花了一天的时间在以前的Stack Overflow答案以及Internet中寻找答案,但是我找不到解决问题的方法

我有一个随着时间推移在美国石油生产的数据框架。数据包括日期列和相应的值。数据的最小可复制代码如下:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('https://raw.githubusercontent.com/Arsik36/SO/master/Oil%20production.csv',parse_dates = ['date'],index_col = 'date')

我使用下面的代码来可视化一段时间内石油生产的总体趋势:

# Visualizing Time Series
df.value.plot(title = 'Oil production over time')

# Specifying naming convention for x-axis
plt.xlabel('Date')

# Specifying naming convention for y-axis
plt.ylabel('Oil production volume')

# Improving visual aesthetics
plt.tight_layout()

# Showing the result
plt.show()

通过在您的环境中运行此代码,您会看到该图显示了值随时间的分布。 我遇到的困难是要么按年份将图分成多个子图(例如1995年至1997年),要么每年在一张图上显示不同的线条

df['1995' : '1997'].value.plot(title = 'Oil production over time',subplots = True)

当我使用此代码时,它仅对1997年的数据进行了正确的子集划分,并且使用subplots = True该图确实是按年份分隔的。但是,通过在您的环境中运行它,您可以看到该图在x轴上按年分隔,但是利用1条线来显示所有3年的结果。我想做的是将一个地块分成1995、1996和1997年的3个子图,或者在一个图中显示3条线,每条线对应一个唯一的年份。

对于我来说,重要的是能够通过将日期列保留为索引列而不必创建任何其他列(如果可能)来解决此问题。

预先感谢您的帮助。

解决方法

您是正确的建议,没有针对python的已实现解决方案,我知道R在fpp2中对此具有实现。

我想出的解决方案是从您的数据中获取每年的数据,并将其连续绘制在for循环中。

years=[1995,1996,1997]

fig,ax=plt.subplots(figsize=(10,30))

for i in years:
    aux=df[df.index.map(lambda x : x.year == i)] #slice the data for each year
    aux.reset_index(inplace=True,drop=True) #we need to drop the index in order to be able to plot all lines in the same timeframe.

    #afterwards an index is given to all the series
    aux.set_index(pd.date_range(pd.to_datetime('01-01-2000'),periods=aux.shape[0],freq='W'),inplace=True)
    ax.set_xticklabels(aux.index,rotation = 90)
    ax.plot(aux.values,label=str(i))
    plt.legend()

fig.autofmt_xdate() #to be able to see the dates clearly

fig.show()

这会产生如下结果:

resulting plot

剩下要做的就是格式化x轴标签,以便仅显示月份。