Python 时间序列分析中如何结合两条折线图进行数据验证

How to combine two line graphs for data validation during time series analysis in Python

我已经分离了我的训练数据来进行验证,并试图按照一个例子来说明如何在一个时间序列图表中绘制训练数据和验证数据,其中线条会连接并在验证数据处改变颜色(请参阅例如我正在关注的图片)。

我非常严格地遵循示例(针对我自己的数据进行了调整),并且得到了两个单独的图表。 示例遵循编码和输出:

Train.Count.plot(figsize=(15,8), title= 'Daily Ridership', fontsize=14, label='train') 
valid.Count.plot(figsize=(15,8), title= 'Daily Ridership', fontsize=14, label='valid') 
plt.xlabel("Datetime") plt.ylabel("Passenger count") plt.legend(loc='best') plt.show()

我的代码(使用设置的不同数据来提供 pandas 数据帧 bananas_train 和 bananas_val 中值的总和)如下:

bananas_train.plot(figsize=(15,8), title= 'Bananas Daily', fontsize=14, label='train')
bananas_val.plot(figsize=(15,8), title= 'Bananas Daily', fontsize=14, label='valid')
plt.xlabel("Date")
plt.ylabel("Quantity Picked")
plt.legend(loc='best')
plt.show()

由于收到语法错误,底线已与原始代码分开。

我尝试使用以下代码重做,但仍然得到两个单独的图表:

#attempt 2
plt.figure(figsize=(28,8))
ax1 = bananas_train.plot(color='blue', grid=True, label='train')
ax2 = bananas_val.plot(color='red', grid=True, label='valid')
plt.xlabel("Date")
plt.ylabel("Quantity Picked")
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
plt.legend(h1+h2, l1+l2, loc='best')
plt.show()

我的结果显示了两个独立的时间序列图表,而不是一个。关于如何合并这两个图表有什么想法吗?

编辑:如果我关注列为该问题重复项的页面... Plot different DataFrames in the same figure 我得到一个包含两条线的图表,但 x 轴从头开始匹配,而不是从最后一行停止的地方继续。 这是我的代码,我尝试按照这些指示进行操作并得到了这个结果:

#attempt 3
ax = bananas_train.plot()
bananas_val.plot(ax=ax)
plt.show()

我需要我的结果继续用新合并的数据绘制的线,而不是重叠线。

下次最好在您的问题中包含一些样本数据。 我相信有更好的方法可以实现你想要的,但我会在这里列出一个:

# get the length of your training and checking set assuming your data are 
# in 2 dataframes (test and check respectively) with a column named after 'count'
t_len=len(test['count'].index)
c_len=len(check['count'].index)

# concaternate your dataframes
test_check= pd.concat([test['count'],check['count']],ignore_index=True)

#create 2 dataframes assigning 0s to training and checking set respectively
test_1=test_check.copy()
check_1= test_check.copy()

test_1.iloc[0:t_len]=0
check_1.iloc[c_len:]=0

#make the plot
test_1.plot(figsize=(15,8),color='blue')
check_1.plot(figsize=(15,8),color='red')