How to draw an arrow in matplotlib if one axis contains time?

Minor confusion here: I want to draw a wind forecast by drawing a series of arrows at the predicted time t (x-axis) with wind speed (y-axis) and an arrow indicating the direction of the wind blowing out. The arrow dimensions must be a given fraction of the plot height, for example. arbitrarily defined as 1/15 of the site height. Since the graph is automatically scaled to the maximum wind speed in the wind list, it follows that:

arrowlength = np.max(wind) / 15.0

      

This should give the length of the arrow in Y units of the patch. The problem is that the X units, however, are not compatible for drawing purposes, because I am using datetime for that. This is how matplotlib gets its panties in a twist when I do the following (this is the code that should work if the x-axis was not a date):

for x,u,v,y in zip(t, windu, windv, wind):
  xcomp = arrowlength * sin(u/v)
  ycomp = arrowlength * cos(u/v)
  arr = Arrow(x-xcomp/2, y-ycomp/2, x+xcomp/2, y+ycomp/2, edgecolor='black')
  ax.add_patch(arr)
arr.set_facecolor('b')

      

These reservoirs are of course where the datetime t (x respectively in the loop) is passed to the Arrow function.

I suppose in the same vein there is a lot, which is a very general question: how to place lines and other annotations in a coordinate grid that does not have the same units in X and Y?

+3


source to share


1 answer


You can use matplotlib.dates

( http://matplotlib.org/api/dates_api.html ) to convert date coordinates to axes using method date2num()

. In the following example, I create an arrow from (Apr 5, 2015, 10) to (Apr 7, 2015, 20):

import matplotlib.pyplot as plt
import matplotlib.dates as md

import datetime

fig = plt.figure()
ax = fig.add_subplot(111)

t0 = datetime.datetime(2015,4,1)
t = [t0+datetime.timedelta(days=j) for j in xrange(20)]
y = range(20)
ax.plot(t, y)

x0 = md.date2num(datetime.datetime(2015,4,5))
y0 = 10
xw = md.date2num(datetime.datetime(2015,4,7)) - x0
yw = 10
arr = plt.Arrow(x0, y0, xw, yw, edgecolor='black')
ax.add_patch(arr)
arr.set_facecolor('b')
fig.autofmt_xdate()
plt.show()

      



enter image description here

+3


source







All Articles