![](/img/trans.png)
[英]Plotting multiple Y values against multiple X values which are different timestamps in matplotlib in the same graph?
[英]Plotting two lists of different length matplotlib against same x value
我有兩個numpy.ndarrays
, bcmonthly
和dailyavg
。
bcmonthly has a length of 12 and shape of (12,)
dailyavg has a length of 364 and shape of (364,)
bcmonthy
是月平均值, dailyavg
是日平均值。 我想針對12個月的x軸繪制兩個變量。
繪制bcmonthly
沒問題,因為它的形狀是12。但是當我同時繪制dailyavg
時,會出現此錯誤:
ValueError: x and y must have same first dimension, but have shapes (12,) and (364,)
下面是我的代碼:
fig = plt.figure()
ax1=fig.add_subplot(111)
ax1.plot(months,bcmonthly,'r') #months is a list months=['jan','feb',..etc]
ax2 = ax1.twinx()
ax2.plot(months, dailyavg)
plt.show()
如果要在與日平均值相同的圖表上繪制每日平均值,則構造兩個數組並將它們相對於幾天的數組繪制可能更容易,然后自己處理標簽。 像這樣
import matplotlib.pyplot as plt
import numpy as np
bcmonthly = np.random.rand(12) # Creates some random example data,
dailyavg = np.random.rand(365) # use your own data in place of this
days = np.linspace(0, 364, 365)
months = ['January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September',
'October', 'November', 'December']
lmonths = [0, 2, 4, 6, 7, 9, 11]
smonths = [3, 5, 8, 10]
month_idx = list()
idx = -15 # Puts the month avg and label in the center of the month
for jj in range(len(months)):
if jj in lmonths:
idx += 31
month_idx.append(idx)
elif jj in smonths:
idx += 30
month_idx.append(idx)
elif jj == 1:
idx += 28
month_idx.append(idx)
fig = plt.figure(figsize=(10,4), dpi=300)
plt.plot(month_idx,bcmonthly,'r')
plt.plot(days, dailyavg, ':', linewidth=1)
plt.xlim([-1,366])
plt.title("Monthly and Daily Averages")
plt.xticks(month_idx, months, rotation=45)
plt.show()
另外,您可以使用ax.plot()
的面向對象方法,但這需要您分別指定刻度標簽和位置,
import matplotlib.pyplot as plt
import numpy as np
bcmonthly = np.random.rand(12)
dailyavg = np.random.rand(365)
days = np.linspace(0, 364, 365)
months = ['January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September',
'October', 'November', 'December']
lmonths = [0, 2, 4, 6, 7, 9, 11]
smonths = [3, 5, 8, 10]
month_idx = list()
idx = -15 # Puts the month avg and label in the center of the month
for jj in range(len(months)):
if jj in lmonths:
idx += 31
month_idx.append(idx)
elif jj in smonths:
idx += 30
month_idx.append(idx)
elif jj == 1:
idx += 28
month_idx.append(idx)
fig = plt.figure(figsize=(10,4), dpi=300)
ax1 = fig.add_subplot(111)
ax1.plot(month_idx,bcmonthly,'r')
ax2 = ax1.twinx()
ax2.plot(days, dailyavg, ':', linewidth=1)
plt.xlim([-1,366])
plt.title("Monthly and Daily Averages")
ax1.set_xticklabels(months, rotation=45)
ax1.set_xticks(month_idx)
plt.show()
在繪制months
與dailyavg
,您需要延長months
以使其長度為364-Matplotlib無法為您決定將364個每日平均值中的每個平均值分配給months
中的12個x值中的哪個,但是您可以自己通過適當長度的x值列表。
因此,在這種情況下,這似乎意味着要創建一個包含"January"
31 "January"
的列表,然后包含"February"
28次,依此類推……直到您達到長度364(取決於缺少的日期?)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.