简体   繁体   中英

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

Slight confusion here: I want to draw a wind forecast by drawing a series of arrows at forecast time t (in the x-axis) at wind speed wind (y-axis) and the arrow pointing in the direction the wind is blowing from. Dimensions of the arrow should be a given fraction of the plot height, eg arbitrarily determined to be 1/15th of the plot height. Since the plot is scaled automatically to the maximum wind speed in the wind list, it follows that:

arrowlength = np.max(wind) / 15.0

That should yield the arrow length in plot Y units. The issue appears to be that the X units however are incompatible for the purposes of drawing because I'm using a datetime for it. So matplotlib gets its knickers in a twist when I do the following (which is the code that should work if the x-axis wasn't a datetime):

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

This tanks of course where the datetime t ( x respectively in the loop) is passed to the Arrow function.

I suppose much in the same vein, that's a very general question: How does one place lines and other annotations into a coordinate grid that doesn't have the same units in X and Y?

You can use matplotlib.dates ( http://matplotlib.org/api/dates_api.html ) to convert a date to axes coordinates, using the date2num() method. In the following example, I create an arrow going from (April 5 2015, 10) to (April 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()

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM