Plot Circle in Pyplot

5/5 - (3 votes)

How to Plot a Circle in Python?

You can easily plot a circle in Matplotlib’s Pyplot library by calling plt.gca() to “get the current axis”. Then call the axis.add_patch() function and pass a plt.Circle() object into it.

For example, the one-liner

plt.gca().add_patch(plt.Circle((0.5, 0.5), 0.2, color='lightblue')) 

adds a lightblue circle to the plot at position x=0.5, y=0.5 with radius r=0.2.

import matplotlib.pyplot as plt

# Add a lightblue circle to the plot at position x=0.5, y=0.5 with radius r=0.2
plt.gca().add_patch(plt.Circle((0.5, 0.5), 0.2, color='lightblue'))

plt.show()

The output after manually rescaling the plot area to be squared instead of rectangled (in which case it would show an “ellipse” rather than a “cirlce”):

How to Plot Multiple Circles in Python?

To plot multiple circles in Python, call plt.gca() to “get the current axis”. Then call the axis.add_patch() function multiple times in a for loop and pass a plt.Circle() object into it.

Here’s an example that plots 5 circles with different colors and radiuses and locations:

import matplotlib.pyplot as plt

# Data for 5 circles
locations = [0.1, 0.3, 0.5, 0.7, 0.9]
colors = ['b', 'g', 'r', 'y', 'grey']
radius = [0.02, 0.04, 0.08, 0.16, 0.32]

# Plot 5 circles
for i in range(len(locations)):
    circle = plt.Circle((locations[i], locations[i]),
                        radius[i], color=colors[i], alpha=0.5)
    plt.gca().add_patch(circle)

plt.show()

Here’s an example:

Beautiful, isn’t it? The nice pastel colors came from setting the alpha channel to 0.5, i.e., they are partially opaque.

🌍 Recommended Tutorial: The Ultimate Guide to Python Matploblib (Video Course Free)