简体   繁体   English

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

[英]How to shift a line in a matplotlib plot?

I am trying to plot two lists in python, one is test1 and other is predictions1 .我试图在 python 中绘制两个列表,一个是test1 ,另一个是predictions1

I wish to plot the first 150 entries of the test1 list and then plot the entries 101- 150 of predictions1 list, so that the two plots get superimposed on one another.我希望绘制test1列表的前 150 个条目,然后绘制predictions1列表的条目 101-150,以便两个图相互叠加。 Here is what I tried:这是我尝试过的:

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

But I am getting the result:但我得到了结果: 在此处输入图片说明

Clearly this is not what I wanted to achieve as I want the red plot to get superimposed over the blue plot towards the end.显然,这不是我想要实现的,因为我希望红色图在最后叠加在蓝色图上。 Please help.请帮忙。

The idea would be to create a list of numbers to use as your x data, from 0 to 150:这个想法是创建一个数字列表用作您的 x 数据,从 0 到 150:

x_data = range(150)

Then slice this so that for the first set of data, your x axis uses numbers 0 to 149. Then the second set of data needs to be sliced to use the numbers 100 to 149.然后将其切片,以便对于第一组数据,您的 x 轴使用数字 0 到 149。然后需要对第二组数据进行切片以使用数字 100 到 149。

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

Note that Python indexing starts at 0, not 1请注意,Python 索引从 0 开始,而不是 1

This suggestion will work for any type of index values (string, dates or integers) as long as they are unique.这个建议适用于任何类型的索引值(字符串、日期或整数),只要它们是唯一的。


Short Answer:简答:

Create a pandas dataframe of the longest series.创建最长系列的熊猫数据框。 This dataframe will have an index.这个数据框将有一个索引。 Get the last 50 index values from that series and associate it with your prediction values in a new dataframe.从该系列中获取最后50 个索引值,并将其与新数据框中的预测值相关联。 Your two dataframes will have different lenghts, so you'll have to merge them together in order to get two series of equal lengths.您的两个数据帧将具有不同的长度,因此您必须merge它们merge在一起以获得两个相等长度的系列。 With this approach, your first 100 values of your prediction values will be empty, but your data will have an associated index so that you can plot it against your test1 series.使用这种方法,您的预测值的前 100 个值将为空,但您的数据将具有关联的索引,以便您可以将其与 test1 系列进行绘制。

The details:详情:

Since you did not share a reproducible dataset, I made some random data that should match the structure of your dataset.由于您没有共享可重现的数据集,因此我制作了一些应该与您的数据集结构相匹配的随机数据。 The first snippet below will reproduce your situation and make two arrays test1 and **predictions1 **available for a suggested solution.下面的第一个片段将重现您的情况,并使两个数组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()

在此处输入图片说明

The following snippet will superimpose predictions1 on test1:以下代码段将在 test1 上叠加预测 1:

# 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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM