Introduction
Matplotlib is a powerful data visualization library in Python. In this lab, we will explore the use of EllipseCollection to draw a collection of ellipses.
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 necessary libraries
We will start by importing the necessary libraries.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import EllipseCollection
Create data for ellipses
We create data for our ellipses in the form of arrays of x-coordinates, y-coordinates, width, height and angle.
x = np.arange(10)
y = np.arange(15)
X, Y = np.meshgrid(x, y)
XY = np.column_stack((X.ravel(), Y.ravel()))
ww = X / 10.0
hh = Y / 15.0
aa = X * 9
Create Ellipse Collection
We create an EllipseCollection with the above data and specify the units to be 'x' and the offsets to be XY.
fig, ax = plt.subplots()
ec = EllipseCollection(ww, hh, aa, units='x', offsets=XY,
offset_transform=ax.transData)
Set the color of ellipses
We set the color of each ellipse in the EllipseCollection based on the sum of its x and y coordinate.
ec.set_array((X + Y).ravel())
Add collection to the plot
We add the EllipseCollection to the plot.
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()
Summary
In this lab, we learned how to use EllipseCollection to draw a collection of ellipses in Matplotlib. We also learned how to set the color of each ellipse based on its x and y coordinate.