簡體   English   中英

如何plot arrays不同長度

[英]How to plot arrays of different lengths

您如何 plot arrays 不同長度但在 x 軸上正確延伸? 下面的代碼生成 2 個數據集,第二個更短。 我對每組數據進行插值,每個數據點使用多個樣本重新采樣數據。 當我 plot 所有數據時,較短的數據集不會延伸到 plot 的末尾。 我不想要子圖,我需要將數據相互疊加。

#!/usr/bin/env python3

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np

num_points = 100

# Generate an array of data, interpolate, re-sample and graph
x1 = np.arange(0, num_points)
y1 = np.cos(x1)
f1 = interpolate.interp1d(x1, y1, kind='cubic')
xnew1 = np.arange(0, num_points - 1, 0.2)
ynew1 = f1(xnew1)  

plt.plot(x1, y1, color='g', label='input 1')
plt.plot(x1, y1, 'o', color='g')
plt.plot(xnew1, ynew1, color='m', label='interp 1')
plt.plot(xnew1, ynew1, '+', color='m')

# Generate ana array different size of data, interpolate, re-sample and graph
x2 = np.arange(0, num_points/2)
y2 = np.sin(x2)
f2 = interpolate.interp1d(x2, y2, kind='cubic')
xnew2 = np.arange(0, (num_points/2) - 1, 0.2)
ynew2 = f2(xnew2)  

plt.plot(x2, y2, color='k', label='input 2')
plt.plot(x2, y2, 'o', color='k')
plt.plot(xnew2, ynew2, color='r', label='interp 2')
plt.plot(xnew2, ynew2, '+', color='r')

plt.legend(loc='upper left')
plt.show()

繪制兩個數據集

如果我理解正確,這可以通過使用共享相同 y 軸的兩個不同軸來完成,如此 matplotlib 示例中所述。

在您的情況下,您可以通過進行以下修改來完成此操作:

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np
num_points = 100

# Generate an array of data, interpolate, re-sample and graph
x1 = np.arange(0, num_points)
y1 = np.cos(x1)
f1 = interpolate.interp1d(x1, y1, kind='cubic')
xnew1 = np.arange(0, num_points - 1, 0.2)
ynew1 = f1(xnew1)  

fig, ax1 = plt.subplots()  # Create the first axis

ax1.plot(x1, y1, color='g', label='input 1')
ax1.plot(x1, y1, 'o', color='g')
ax1.plot(xnew1, ynew1, color='m', label='interp 1')
ax1.plot(xnew1, ynew1, '+', color='m')

ax2 = ax1.twiny()          # Create a twin which shares the y-axis

# Generate an array different size of data, interpolate, re-sample and graph
x2 = np.arange(0, num_points/2)
y2 = np.sin(x2)
f2 = interpolate.interp1d(x2, y2, kind='cubic')
xnew2 = np.arange(0, (num_points/2) - 1, 0.2)
ynew2 = f2(xnew2)  

ax2.plot(x2, y2, color='k', label='input 2')
ax2.plot(x2, y2, 'o', color='k')
ax2.plot(xnew2, ynew2, color='r', label='interp 2')
ax2.plot(xnew2, ynew2, '+', color='r')
plt.figlegend(loc='upper left', bbox_to_anchor=(0.065, 0.3, 0.5, 0.5))
plt.show()

這會給你一些看起來像

修改后代碼的輸出

編輯

為了正確顯示圖例,您可以為所有子圖構建一個圖例,如本演示中所述。 請注意,使用此方法將需要對圖例的邊界框進行一些人工處理,並且有比我在行中指定 4 元組浮點數更簡潔的方法來做到這一點

plt.figlegend(loc='upper left', bbox_to_anchor=(0.065, 0.3, 0.5, 0.5))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM