python - Arrow direction set by data, but length set by figure size -
i draw arrow indicating gradient of function @ point, pointing in direction tangent function. length of arrow proportional axis size, visible @ zoom level.
say want draw derivative of x^2
@ x=1
(the derivative 2
). here 2 things tried:
import matplotlib.pyplot plt import numpy np fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(0, 2, 1000) y = x**2 ax.plot(x, y) x, y = (1.0, 1.0) grad = 2.0 # fixed size, wrong direction len_pts = 40 end_xy = (len_pts, len_pts*grad) ax.annotate("", xy=(x, y), xycoords='data', xytext=end_xy, textcoords='offset points', arrowprops=dict(arrowstyle='<-', connectionstyle="arc3")) # fixed direction, wrong size len_units = 0.2 end_xy = (x+len_units, y+len_units*grad) ax.annotate("", xy=(x, y), xycoords='data', xytext=end_xy, textcoords='data', arrowprops=dict(arrowstyle='<-', connectionstyle="arc3")) ax.axis((0,2,0,2)) plt.show()
here's @ 2 zoom levels. clear, i want red line's length , black line's direction:
in case, sounds want quiver
. scaling options bit confusing @ first, , default behavior different want. however, entire point of quiver give control on how size, angles, , scaling interact resize plot.
for example:
import matplotlib.pyplot plt import numpy np fig, ax = plt.subplots() x = np.linspace(0, 2, 1000) y = x**2 ax.plot(x, y) x0, y0 = 1.0, 1.0 dx, dy = 1, 2 length = 1.25 # in inches dx, dy = length * np.array([dx, dy]) / np.hypot(dx, dy) ax.quiver(x0, y0, dx, dy, units='inches', angles='xy', scale=1, scale_units='inches', color='red') ax.axis((0, 2, 0, 2)) plt.show()
the key part here
units='inches', angles='xy', scale=1
angles='xy'
specifies want rotation/angle of arrow in data units (i.e. match gradient of plotted curve, in case).
scale=1
tells not autoscale length of arrow, , instead draw size give units we've specified.
units='inches'
tells quiver
interpret our dx, dy
being in inches.
i'm not sure scale_units
needed in case (it should default same units
), allows arrow have different length unit width unit.
and resize plot, angle stays in data units, length stays in inches (i.e. constant length on-screen):
Comments
Post a Comment