search
Search
Publish
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
search
keyboard_voice
close
Searching Tips
Search for a recipe: "Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
share
thumb_up_alt
bookmark
arrow_backShare
Twitter
Facebook

Drawing arrows in Matplotlib

Programming
chevron_right
Python
chevron_right
Matplotlib
chevron_right
Cookbooks
chevron_right
Graphs Cookbook
schedule Jul 1, 2022
Last updated
local_offer PythonMatplotlib
Tags

In Matplotlib, use the arrow(~) method to draw arrows:

plt.xlim(-5,5)
plt.ylim(-5,5)

# (starting_x, starting_y, dx, dy, ...)
plt.arrow(-2, -1, 3, 5, head_width=0.5, head_length=0.5, color='black')
plt.show()

This generates the following:

The line (without the arrow) begins at (-2,-1) and ends at (-2+3,-1+5)=(1,4). However, the presence of the arrow makes the length of the line a slightly longer. To make the arrow end at the specified endpoint (i.e. (1,4) in this case), set the parameter length_includes_head=True.

The head_width and head_length function, otherwise you will see just a line without the arrow.

Helper function to draw an arrow given starting and ending coordinate

Matplotlib asks you to provide dx and dy to plot your arrow, yet most of the time, you have the starting coordinate and ending coordinate in hand. In these cases, you might prefer to use the following helper function:

def draw_arrow(plt, arr_start, arr_end):
dx = arr_end[0] - arr_start[0]
dy = arr_end[1] - arr_start[1]
plt.arrow(arr_start[0], arr_start[1], dx, dy, head_width=0.5, head_length=0.5, length_includes_head=True, color='black')

We can use the function like so:

plt.xlim(-5,5)
plt.ylim(-5,5)
draw_arrow(plt, [-1,-2], [3,4])
plt.show()

This generates the following:

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!