簡體   English   中英

繪制不同索引長度的兩個線圖,其中沒有數據的斷開連接

[英]Plotting two line plots of different index lengths with disconnects where there is no data

我需要在一對軸上繪制兩個數據集。 每個數據集包含兩個列表:

  • 日期(格式為YYYYMM)
  • 價值觀(月平均值)

我遇到的問題是,一個數據集只包含夏季(以紅色繪制),而另一個數據包含每月(以藍色繪制)。 結果,我得到了如下圖像: 紅色和藍色線圖均從圖的左側連續延伸到右側。

但是,我不希望夏季的線條圖(紅色)在幾年之間連接起來。 也就是說,我不想在200208和200306的數據點之間畫一條線。我想在紅線上存在數據不存在的間隙,就像Joe Kuan的這張圖。

藍線有連續數據。紅線有沒有數據存在的中斷。

我用來繪制第一張圖片的代碼是:

#data1
x = monthly_avgs_aod.index.tolist()
x = [dt.datetime.strptime(i, '%Y%m') for i in x] 
y = monthly_avgs_aod.values.tolist()

#data2
q = monthly_avgs_pm.index.tolist()
q = [dt.datetime.strptime(i, '%Y%m') for i in q] 
w = monthly_avgs_pm.values.tolist()
plt.plot(q, w, '-r')    
plt.plot(x, y, ':b')

我使用的數據如下所示:

#data1
x=['200101','200102','200103','200104','200105','200106','200107','200108','200109','200110','200111','200112','200201','200202','200203','200204','200205','200206','200207','200208','200209']
y=[30.2,37.6,34.7,27.1,31.9,43.9,42.4,42.3,34.4,40.0,47.2,40.8,34.7,27.1,31.9,43.9,42.4,42.3,34.4,40.0,47.2]

#data2   
q=['200106','200107','200108','200206','200207','200208']
w=[19.7,18.6,15.2,17.3,16.9,18.2]

任何幫助都將不勝感激。

在這種情況下最簡單的解決方案,其中兩個日期列表共享相同的日期(即一個月可能在列表中或不在列表中),將填充僅包含夏季月份的列表,其中包含None值的值沒有數據並將其繪制在相同的x ,以繪制完整的y列表。

import matplotlib.pyplot as plt
import datetime as dt
#data1
x=['200101','200102','200103','200104','200105','200106','200107','200108',
   '200109','200110','200111','200112','200201','200202','200203','200204',
   '200205','200206','200207','200208','200209']
x = [dt.datetime.strptime(i, '%Y%m') for i in x] 
y=[30.2,37.6,34.7,27.1,31.9,43.9,42.4,42.3,34.4,40.0,47.2,
   40.8,34.7,27.1,31.9,43.9,42.4,42.3,34.4,40.0,47.2]

#data2   
q=['200106','200107','200108','200206','200207','200208']
q = [dt.datetime.strptime(i, '%Y%m') for i in q] 
w=[19.7,18.6,15.2,17.3,16.9,18.2]

for i, xi in enumerate(x):
    if xi not in q:
        w.insert(i, None)


plt.plot(x,y, '-r')    
plt.plot(x,w,':b')


plt.show()

在此輸入圖像描述

為每組連續月份創建單獨的列表。 分別繪制每個列表。

sublist_q = [q.pop()] # algorithm reverses order, shouldn't matter
sublist_w = [w.pop()]
while q:
    # Just-popped last month is sublist_q[-1] .
    # Next-to-pop month preceding it in data is q[-1]%100 .
    # Represent next-to-pop December as 0 with q[-1]%100%12
    # so that contiguous months always have a difference of 1
    if sublist_q[-1] - q[-1]%100%12 != 1: # True if months not contiguous
        # We're done with the current sublists. 
        plot(sublist_q, sublist_w, 'r-o') # 'o' to show singletons
        # Reinitialize
        sublist_q = [q.pop()]
        sublist_w = [w.pop()]
    else:
        sublist_q.append(q.pop()) 
        sublist_w.append(w.pop())

暫無
暫無

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

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