Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use pyplot.arrow or patches.Arrow in matplotlib?
Matplotlib provides multiple ways to draw arrows: pyplot.arrow() for simple arrows and patches.FancyArrowPatch() for advanced styling. Both methods allow you to create directional indicators in your plots.
Using pyplot.arrow()
The pyplot.arrow() function creates a simple arrow from starting coordinates to ending coordinates ?
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
# Draw a simple arrow
plt.arrow(x=0.2, y=0.2, dx=0.6, dy=0.6,
head_width=0.05, head_length=0.1,
fc='blue', ec='blue')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.title('Simple Arrow using pyplot.arrow()')
plt.show()
Using patches.FancyArrowPatch()
The FancyArrowPatch class provides more styling options and better control over arrow appearance ?
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
plt.figure(figsize=(8, 6))
# Create figure and axis
fig, ax = plt.subplots()
# Define arrow coordinates
x_tail = 0.1
y_tail = 0.1
x_head = 0.9
y_head = 0.9
# Create fancy arrow
arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (x_head, y_head),
mutation_scale=100, color='green',
arrowstyle='->')
ax.add_patch(arrow)
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.title('Fancy Arrow using patches.FancyArrowPatch()')
plt.show()
Multiple Arrows with Different Styles
You can create multiple arrows with various styles and colors in the same plot ?
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig, ax = plt.subplots(figsize=(10, 8))
# Different arrow styles
arrow_styles = ['->', '-|>', '<-', '<->', '<|-|>']
colors = ['red', 'blue', 'green', 'orange', 'purple']
positions = [(0.1, 0.8), (0.1, 0.6), (0.1, 0.4), (0.1, 0.2), (0.1, 0.0)]
for i, (style, color, pos) in enumerate(zip(arrow_styles, colors, positions)):
arrow = mpatches.FancyArrowPatch(pos, (0.8, pos[1]),
arrowstyle=style,
color=color,
mutation_scale=20)
ax.add_patch(arrow)
ax.text(0.85, pos[1], style, fontsize=12, va='center')
ax.set_xlim(0, 1)
ax.set_ylim(-0.1, 0.9)
ax.set_title('Different Arrow Styles')
plt.show()
Parameters Comparison
| Method | Key Parameters | Best For |
|---|---|---|
pyplot.arrow() |
x, y, dx, dy, head_width, head_length | Simple directional arrows |
FancyArrowPatch() |
posA, posB, arrowstyle, mutation_scale | Styled arrows with advanced options |
Conclusion
Use pyplot.arrow() for simple directional indicators and patches.FancyArrowPatch() for styled arrows with advanced customization options. FancyArrowPatch provides better control over appearance and supports multiple arrow styles.
