Matplotlib Ellipse with Orientation Arrow

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to draw an ellipse with an orientation arrow using Matplotlib. Ellipses are a type of shape that are commonly used in data visualization to represent data. By adding an orientation arrow to an ellipse, you can provide additional information about the direction of the data.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import Matplotlib and Create a Figure and Axis

First, you need to import Matplotlib and create a figure and axis. The figure and axis are the containers for your plot.

import matplotlib.pyplot as plt

## Create a figure and axis
fig, ax = plt.subplots(subplot_kw={"aspect": "equal"})

Create an Ellipse

Next, you need to create an ellipse using the Ellipse class. You can specify the center of the ellipse, the width and height of the ellipse, and the angle of rotation.

from matplotlib.patches import Ellipse

ellipse = Ellipse(
    xy=(2, 4),
    width=30,
    height=20,
    angle=35,
    facecolor="none",
    edgecolor="b"
)
ax.add_patch(ellipse)

Add an Orientation Arrow

You can add an orientation arrow to the ellipse by plotting a marker at the end point of the minor axis. You can use the get_co_vertices() method to get the coordinates of the vertices of the ellipse. Then, you can use the Affine2D() class to rotate the marker to match the angle of the ellipse.

from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D

## Plot an arrow marker at the end point of minor axis
vertices = ellipse.get_co_vertices()
t = Affine2D().rotate_deg(ellipse.angle)
ax.plot(
    vertices[0][0],
    vertices[0][1],
    color="b",
    marker=MarkerStyle(">", "full", t),
    markersize=10
)

Reverse the Orientation Arrow

If you want to reverse the orientation arrow, you can switch the marker type from > to <.

## To reverse the orientation arrow, switch the marker type from > to <.
ax.plot(
    vertices[0][0],
    vertices[0][1],
    color="b",
    marker=MarkerStyle("<", "full", t),
    markersize=10
)

Display the Plot

Finally, you can display the plot using the show() method.

plt.show()

Summary

Congratulations! You have learned how to draw an ellipse with an orientation arrow using Matplotlib. This technique can be useful for visualizing data that has a direction.

Other Python Tutorials you may like