我无法在matplotlib中的两点之间画一条线

时间:2020-05-13 22:30:15

标签: python datetime matplotlib

我希望使用月度数据作为日期时间变量,在y轴上的两个点上突出显示y轴上的两个点。我使用的代码适用于年度数据。

我做什么

这是绘制未编辑图表的代码

timeSelection = (co2data_monthly.index >= dt.datetime(2019, 12, 1))
fig, ax = plt.subplots(1, 1, figsize = (10, 8))
ax.plot(x[timeselection],color = 'black', linewidth = 3)

有效。这段代码绘制了我计划连接的点

ax.plot(dt.datetime(2020, 2, 1), x[dt.datetime(2019, 12, 1)], 'ro') 
ax.plot(dt.datetime(2020, 2, 1), x[dt.datetime(2020, 2, 1)], 'ro') 

也可以。

问题

我正在努力在这两点之间划清界限。我使用这段代码

from matplotlib import collections as mc
lines = [[(dt.DatetimeIndex(2020, 2, 1), x[dt.datetime(2019, 12, 1)]), (dt.DatetimeIndex(2020, 2, 1), x[dt.datetime(2020, 2, 1)])]]
lc = mc.LineCollection(lines, linewidths=2, color = 'red', linestyle = '--')
ax.add_collection(lc)

在出现以下错误之前

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-428443093c1a> in <module>
      7 ax.plot(dt.datetime(2020, 2, 1), x[dt.datetime(2020, 2, 1)], 'ro')
      8 lines = [[(dt.datetime(2020, 2, 1), x[dt.datetime(2019, 12, 1)]), (dt.datetime(2020, 2, 1), x[dt.datetime(2020, 2, 1)])]]
----> 9 lc = mc.LineCollection(lines, linewidths=2, color = 'red', linestyle = '--')
     10 ax.add_collection(lc)
     11 #ax.axvline(dt.datetime(2019, 12, 1), linestyle ='--', color = 'red')

~\anaconda3\lib\site-packages\matplotlib\collections.py in __init__(self, segments, linewidths, colors, antialiaseds, linestyles, offsets, transOffset, norm, cmap, pickradius, zorder, facecolors, **kwargs)
   1358             **kwargs)
   1359 
-> 1360         self.set_segments(segments)
   1361 
   1362     def set_segments(self, segments):

~\anaconda3\lib\site-packages\matplotlib\collections.py in set_segments(self, segments)
   1367         for seg in segments:
   1368             if not isinstance(seg, np.ma.MaskedArray):
-> 1369                 seg = np.asarray(seg, float)
   1370             _segments.append(seg)
   1371 

~\anaconda3\lib\site-packages\numpy\core\_asarray.py in asarray(a, dtype, order)
     83 
     84     """
---> 85     return array(a, dtype, copy=False, order=order)
     86 
     87 

TypeError: float() argument must be a string or a number, not 'datetime.datetime'

0 个答案:

没有答案