In this tutorial we will discuss how we can go about plotting Circles and Ellipses with Shapely. There is no actual “Circle” or “Ellipse” Class in Shapely, so people do often get confused in how this is done.
Luckily, the solution is actually quite simple. All we have to do is use the Point Class in Shapely, and apply a few special operations on it. Lets get started with the tutorial!
Plotting Circles in Shapely
Normally when we create a “Point” object in Shapely, it is just a single dot. This has no area or length by default. However, there a special method called “buffer” which we can use to add a “radius” to this point. As you might expect, this creates a Circle.
Here is the code along with output (which we visualized in matplotlib).
from shapely.geometry import Point
circle = Point(5, 5).buffer(3)
Interestingly if we print this object, we will notice that it is actually a Polygon, that consists of dozens of points. If we you increase the resolution parameter, the number of points increase, which results in an even smoother circle. (The default value is pretty good for most cases though).
Here is a lower resolution circle, which is more obvious to the naked eye.
circle = Point(5, 5).buffer(3, resolution=3)
Plotting Ellipses in Shapely
Plotting ellipses is a bit trickier, because we can’t use the previous method. Luckily, we can still do this without having to resort to something overly complicated.
First we create a simple point, with a radius of 1 (basically a unit circle).
circle = Point(0, 0).buffer(1)
Next we take this circle, and pass it into the shapely.affinity.scale() function, which basically “scales” this circle to the aspect ratio that we desire.
Here is the complete code for it. Don’t forget to make that extra import.
import shapely.affinity
from shapely.geometry import Point
circle = Point(10, 10).buffer(1)
ellipse = shapely.affinity.scale(circle, 5, 10)
Just like before, the ellipse is also a Polygon.
Interesting in learning more about Shapely? Give our Shapely Tutorial a read!
This marks the end of the Plotting Circles and Ellipses with Shapely Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.