如何在 matplotlib 绘图中移动一条线?

7

我正试图在Python中绘制两个列表,一个是test1,另一个是predictions1

我希望能够绘制test1列表的前150个条目,然后再绘制predictions1列表的101-150个条目,使得两个绘图重叠在一起。这是我的尝试:

import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))
plt.plot(test1[1:150])
plt.plot(predictions1[101:150], color='red')
plt.show()

但我得到的结果是: enter image description here 很明显这并不是我想要实现的,因为我希望红色曲线在末尾叠加在蓝色曲线上。请帮忙解决。

您没有为“plot”提供任何X数据,因此Matplotlib将自动生成X数据。您可以手动创建X数据,使得predictions1将绘制在test1右侧。 - DavidG
@DavidG,你能否详细解释一下?我对Python不是很熟悉。 - The Doctor
这是您的pyplot.plot()函数的文档。如果您只是对如何处理Python有问题,那么您应该能够理解它。第一个参数是X轴,第二个参数是Y轴。 - IMCoins
2个回答

4
这个想法是创建一个数字列表作为你的x数据,从0到150:
x_data = range(150)

然后slice对数据进行切片,这样第一组数据的x轴使用0到149的数字。接着需要将第二组数据切片,使用100到149的数字。

plt.plot(x_data[:], test1[:150])
plt.plot(x_data[100:], predictions1[100:150], color='red')

请注意,Python的索引从0开始,而不是1。

我理解了你的做法。我也尝试了同样的方法,但是结果并不理想。红色曲线完全向右移动到蓝色曲线的位置,而我希望在101-150的值范围内,红色曲线能够与蓝色曲线重叠。比如说,我有一个从1到150的test1图表。然后在同一张图表和坐标轴上,我有一个从101到150的predictions1图表。 - The Doctor
@TheDoctor,请查看我的更新答案,看看是否解决了问题。 - DavidG
好的,就这样了。非常感谢 :) - The Doctor

1
这个建议适用于任何类型的索引值(字符串、日期或整数),只要它们是唯一的。

简短回答:

创建一个最长序列的pandas数据帧,该数据帧将具有索引。从该系列中获取最后50个索引值,并将其与新数据帧中的预测值相关联。您的两个数据帧长度不同,因此您需要merge它们在一起,以获得两个等长的系列。使用这种方法,您的前100个预测值将为空,但是您的数据将具有相关联的索引,以便您可以将其与test1系列进行绘图。

细节:

由于您没有分享可重现的数据集,我制作了一些随机数据,应该与您的数据集结构相匹配。下面的第一个代码段将复制您的情况,并使两个数组test1和**predictions1**可用于建议的解决方案。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(123456)
rows = 150
df = pd.DataFrame(np.random.randint(-4,5,size=(rows, 1)), columns=['test1'])
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df['test1'] = df['test1'].cumsum()

# Get the last 50 values of test1 (as array instead of dataframe)
# to mimic the names and data types of your source data 
test1 = df['test1'].values
predicionts1 = df['test1'].tail(50).values
predictions1 = predicionts1*1.1

# Reproducing your situation:
import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))
plt.plot(test1)
plt.plot(predictions1, color = 'red')
plt.show()

enter image description here

以下代码片段将在test1上叠加predictions1:
# Make a new dataframe of your prediction values
df_new = pd.DataFrame(test1)
df_new.columns = ['test1']

# Retrieve index values
new_index = df_new['test1'].tail(len(predictions1)).index

# Make a dataframe with your prediction values and your index
new_series = pd.DataFrame(index = new_index, data = predictions1)

# Merge the dataframes
df_new = pd.merge(df_new, new_series, how = 'left', left_index=True, right_index=True)
df_new.columns = ['test1', 'predictions1']

# And plot it
import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))
plt.plot(df_new['test1'])
plt.plot(df_new['predictions1'], color = 'red')
plt.show()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接