gpt4 book ai didi

python - 绘制不同索引长度的两条线图,在没有数据的情况下断开连接

转载 作者:行者123 更新时间:2023-11-30 22:29:55 26 4
gpt4 key购买 nike

我有两个数据集,需要在一对轴上绘制。每个数据集包含两个列表:

  • 日期(格式为 YYYYMM)
  • 值(月平均值)

我遇到的问题是一个数据集仅包含夏季月份(以红色绘制),而另一个数据集包含每个月(以蓝色绘制)。结果,我得到了如下所示的图像:Red and blue line plots both extend continuously from left side to right side of a graph.

但是,我不希望夏季月份(红色)的线图在年份之间连接。也就是说,我不想在 200208 和 200306 的数据点之间画一条线。我希望在不存在数据的红线上有一个间隙,就像 Joe Kuan 中的这张图一样。 .

Blue line has continuous data. Red line has breaks where no data exist.

我用来绘制第一张图像的代码是:

#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 值,并将其与绘制完整 y 列表的相同 x 进行绘制。

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()

enter image description here

关于python - 绘制不同索引长度的两条线图,在没有数据的情况下断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46208020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com