How to Use Matplotlib fill_between to Shade a Circle

I often get asked how to create visually appealing plots that go beyond simple lines and scatter plots. One common challenge is shading complex shapes like circles. While Matplotlib’s fill_between function is typically used for shading areas between curves, you can cleverly adapt it to shade inside a circle.

In this article, I will walk you through how to use Matplotlib’s fill_between function to fill the area inside a circle in Python. You will learn multiple methods to achieve this, including a direct approach using parametric equations and a more advanced technique involving masking.

Use Matplotlib fill_between for Circles

Matplotlib is a versatile plotting library in Python, widely used for data visualization. The fill_between function is primarily designed to fill the area between two curves along the x-axis. But with a bit of creativity, you can use it to fill areas bounded by any function, including circles.

Circles are fundamental in many fields, from plotting confidence intervals in statistics to representing geographic areas on maps. Using fill_between allows you to control the shading precisely and customize it with colors, transparency, and patterns.

Method 1: Fill a Circle Using Parametric Equations and fill_between

The circle equation centered at the origin with radius ( r ) is:

[
x^2 + y^2 = r^2
]

We can solve for ( y ):

[
y = \pm \sqrt{r^2 – x^2}
]

Using this, we can plot the upper semicircle ( y = +\sqrt{r^2 – x^2} ) and the lower semicircle ( y = -\sqrt{r^2 – x^2} ). Then, fill_between can shade the area between these two curves.

Here is a full example of how to do this in Python:

import numpy as np
import matplotlib.pyplot as plt

# Circle parameters
radius = 5
center_x, center_y = 0, 0

# Create x values from -radius to +radius
x = np.linspace(center_x - radius, center_x + radius, 500)

# Calculate the upper and lower semicircle y-values
y_upper = center_y + np.sqrt(radius**2 - (x - center_x)**2)
y_lower = center_y - np.sqrt(radius**2 - (x - center_x)**2)

# Plot the circle outline
plt.plot(x, y_upper, color='blue')
plt.plot(x, y_lower, color='blue')

# Use fill_between to shade the area inside the circle
plt.fill_between(x, y_lower, y_upper, color='skyblue', alpha=0.5)

# Set equal aspect ratio to make the circle look perfect
plt.gca().set_aspect('equal', adjustable='box')

# Add title and labels
plt.title('Shading a Circle Using Matplotlib fill_between in Python')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

plt.grid(True)
plt.show()

I executed the above example code and added the screenshot below.

Use Matplotlib fill_between to Shade Circle
  • I created an array of x-values spanning the diameter of the circle.
  • For each x, I computed the corresponding y-values for the upper and lower semicircles.
  • The fill_between function fills the area between these two curves.
  • Setting the aspect ratio to ‘equal’ ensures the circle isn’t distorted.

This method is easy and effective for circles centered at any point by adjusting center_x and center_y.

Method 2: Fill a Circle Using Polar Coordinates and fill_between

Another way to plot and fill a circle is by using polar coordinates. This is especially useful when you want to fill sectors or arcs of a circle.

Here’s how to fill a full circle using polar coordinates and fill_between:

import numpy as np
import matplotlib.pyplot as plt

# Circle parameters
radius = 5
center_x, center_y = 0, 0

# Create theta values from 0 to 2*pi
theta = np.linspace(0, 2 * np.pi, 500)

# Convert polar coordinates to Cartesian coordinates
x = center_x + radius * np.cos(theta)
y = center_y + radius * np.sin(theta)

# Since fill_between works along x-axis, sort x and corresponding y values
sorted_indices = np.argsort(x)
x_sorted = x[sorted_indices]
y_sorted = y[sorted_indices]

# Find y_upper and y_lower for each x
# For a perfect circle, y_upper and y_lower can be split by median y
y_upper = np.maximum(y_sorted, center_y)
y_lower = np.minimum(y_sorted, center_y)

plt.plot(x, y, color='green')

# Fill between y_lower and y_upper
plt.fill_between(x_sorted, y_lower, y_upper, color='lightgreen', alpha=0.5)

plt.gca().set_aspect('equal', adjustable='box')
plt.title('Circle Filled Using Polar Coordinates and fill_between in Python')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()

I executed the above example code and added the screenshot below.

Matplotlib fill_between to Shade Circle
  • I generated points around the circle using polar coordinates.
  • To use fill_between, I sorted the x-values and separated the y-values into upper and lower halves.
  • This approach is more complex but lays the foundation for filling partial arcs or sectors.

Method 3: Use Masking to Fill a Circle Area on a Grid

For more complex scenarios, such as filling circles over scatter plots or heatmaps, I use masking on a grid.

Here’s how to fill a circle using a mask and Matplotlib’s imshow with fill_between for edges:

import numpy as np
import matplotlib.pyplot as plt

# Grid parameters
grid_size = 100
radius = 30
center = (50, 50)

# Create a grid of coordinates
x = np.arange(0, grid_size)
y = np.arange(0, grid_size)
X, Y = np.meshgrid(x, y)

# Create mask for points inside the circle
mask = (X - center[0])**2 + (Y - center[1])**2 <= radius**2

# Plot grid with masked circle area
plt.imshow(mask, cmap='Blues', origin='lower')

plt.title('Filling Circle Area Using Masking in Python')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

I executed the above example code and added the screenshot below.

Use fill_between to Shade Circle in Matplotlib
  • I created a 2D grid and applied a boolean mask for points inside the circle.
  • Using imshow, I visualized the filled circle area.
  • This method is useful for image processing or when working with pixel data.

Tips for Using fill_between in Python Matplotlib

  • Always set the aspect ratio to ‘equal’ when working with circles to avoid distortion.
  • Use transparency (alpha parameter) to overlay shaded areas without hiding other plot elements.
  • Combine fill_between with other plot elements like scatter or line plots to create rich visualizations.
  • For USA-specific data, you can overlay circles on maps to represent regions or statistical areas.

I hope you found this tutorial on how to shade a circle using Matplotlib’s fill_between function in Python helpful. Whether you are visualizing statistical confidence intervals, geographic data, or simply want to enhance your plots, these methods provide flexible ways to work with circles.

If you want to explore more advanced plotting techniques or customize your plots further, keep experimenting with Matplotlib’s wide range of features. Happy coding!

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.