简体   繁体   中英

Matplotlib: plot arbitrary vectors on polar axes

There are previous questions about quiver plots on polar axes in matplotlib, however they concern vector fields. I'm interested in drawing arbitrary vectors on polar axes. If there is a genuine duplicate, please link it.

I'm writing some software which concerns a circular world. I'm plotting an agent's trajectory from the centre of a circular arena to the edge. This is visualised by drawing a vector from the centre of the circle to the edge. I'm trying to use matplotlib's quiver plot to plot vectors on a set of polar axes. Here's a minimum working example:

import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='polar')

    # Plot origin (agent's start point)
    ax.plot(0, 0, color='black', marker='o', markersize=5)

    # Plot agent's path
    ax.quiver((0, 0), (0, 1), color='black')

    # Example of where (0, 1) should be
    ax.plot(0, 1, color='black', marker='o', markersize=5)

    # Plot configuration
    ax.set_rticks([])
    ax.set_rmin(0)
    ax.set_rmax(1)
    ax.set_thetalim(-np.pi, np.pi)
    ax.set_xticks(np.linspace(np.pi, -np.pi, 4, endpoint=False))
    ax.grid(False)
    ax.set_theta_direction(-1)
    ax.set_theta_zero_location("N")

    plt.show()

If you run the code, you get this plot

The plot shows the origin plotted correctly, an example point at (0, 1) to show where the vector should end, then the vector itself which appears far too short (though the direction is correct). From the docs , I understand that quiver takes cartesian coordinates (x,y) denoting the start point of the vector and (u,v) denoting the vector's direction. In my previous experience with quiver (u,v) essentially denotes where the vector's tip will be, so in this case we'd expect the vector to be drawn from (0,0) to (0,1) which isn't the case and I don't know why.

In short, I want to be able to draw arbitrary vectors on a set of polar axes and quiver isn't working as I expected. Three questions:

  1. Is my code actually sensible given my goal? I want to draw a unit vector from the origin to the edge of the polar plot.

  2. Am I completely misunderstanding how to use quiver ?

  3. How can I draw arbitrary vectors on polar axes in matplotlib? I know about arrow and I'm going to give that a try though initial attempts were unsuccessful.

Short of using a standard plot and just defining my own polar system within it I'm completely stumped.

You did not specify u and v in ax.quiver(x,y,u,v) . To make sure the arrow is 1 unit long you will need to set the scale und units as well.

ax.quiver(0,0,0,1, color='black', angles="xy", scale_units='xy', scale=1.)

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