我需要在一对轴上绘制两个数据集。每个数据集包含两个列表:
我遇到的问题是,一个数据集仅包含夏季(以红色绘制),而另一个数据集包含每月(以蓝色绘制)。结果,我得到了如下图像:
但是,我不希望夏季的线条图(红色)在几年之间连接。也就是说,我不想在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]
对此有任何帮助将不胜感激。
答案 0 :(得分:2)
在这种情况下最简单的解决方案,即两个日期列表共享相同的日期(即一个月可能在列表中或不在列表中),将填充仅包含{{1的夏季月份的列表在没有数据的位置处的值,并将其映射到与完整None
列表相对的相同x
。
y
答案 1 :(得分:1)
为每组连续月份创建单独的列表。分别绘制每个列表。
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())