簡體   English   中英

如何在 matplotlib 圖中移動一條線?

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

我試圖在 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()

但我得到了結果: 在此處輸入圖片說明

顯然,這不是我想要實現的,因為我希望紅色圖在最后疊加在藍色圖上。 請幫忙。

這個想法是創建一個數字列表用作您的 x 數據,從 0 到 150:

x_data = range(150)

然后將其切片,以便對於第一組數據,您的 x 軸使用數字 0 到 149。然后需要對第二組數據進行切片以使用數字 100 到 149。

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

請注意,Python 索引從 0 開始,而不是 1

這個建議適用於任何類型的索引值(字符串、日期或整數),只要它們是唯一的。


簡答:

創建最長系列的熊貓數據框。 這個數據框將有一個索引。 從該系列中獲取最后50 個索引值,並將其與新數據框中的預測值相關聯。 您的兩個數據幀將具有不同的長度,因此您必須merge它們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()

在此處輸入圖片說明

以下代碼段將在 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