Ellipse with Units

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, you will learn how to compare the ellipse generated with arcs versus a polygonal approximation using Python Matplotlib.

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 Libraries

To begin, we will import the necessary libraries.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patches

Set Ellipse Parameters

In this step, we will set the parameters for the ellipse.

xcenter, ycenter = 0.38, 0.52
width, height = 0.1, 0.3
angle = -30

Generate Ellipse using Arcs

In this step, we will generate the ellipse using arcs.

theta = np.deg2rad(np.arange(0.0, 360.0, 1.0))
x = 0.5 * width * np.cos(theta)
y = 0.5 * height * np.sin(theta)

rtheta = np.radians(angle)
R = np.array([
    [np.cos(rtheta), -np.sin(rtheta)],
    [np.sin(rtheta),  np.cos(rtheta)],
    ])

x, y = np.dot(R, [x, y])
x += xcenter
y += ycenter

Generate Ellipse using Polygonal Approximation

In this step, we will generate the ellipse using a polygonal approximation.

theta = np.deg2rad(np.arange(0.0, 360.0, 1.0))
x = 0.5 * width * np.cos(theta)
y = 0.5 * height * np.sin(theta)

rtheta = np.radians(angle)
R = np.array([
    [np.cos(rtheta), -np.sin(rtheta)],
    [np.sin(rtheta),  np.cos(rtheta)],
    ])

x, y = np.dot(R, [x, y])
x += xcenter
y += ycenter

Plot Ellipse using Arcs

In this step, we will plot the ellipse using arcs.

fig = plt.figure()
ax = fig.add_subplot(211, aspect='auto')
ax.fill(x, y, alpha=0.2, facecolor='yellow',
        edgecolor='yellow', linewidth=1, zorder=1)

e1 = patches.Arc((xcenter, ycenter), width, height,
                 angle=angle, linewidth=2, fill=False, zorder=2)

ax.add_patch(e1)

Plot Ellipse using Polygonal Approximation

In this step, we will plot the ellipse using a polygonal approximation.

ax = fig.add_subplot(212, aspect='equal')
ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
e2 = patches.Arc((xcenter, ycenter), width, height,
                 angle=angle, linewidth=2, fill=False, zorder=2)

ax.add_patch(e2)
fig.savefig('arc_compare')

plt.show()

Summary

In this lab, you learned how to compare the ellipse generated with arcs versus a polygonal approximation using Python Matplotlib. You learned how to set ellipse parameters, generate ellipses using arcs and a polygonal approximation, and plot them using Matplotlib.

Other Python Tutorials you may like