Working with data in Python often requires more than just drawing lines on a chart. Over my years of experience as a Python developer, I’ve found that shading specific areas makes a massive difference.
When I first started using the Python Matplotlib library, I struggled to highlight the space between two trends. It felt like my charts were missing that professional “pop” that helps a client understand the data instantly.
That changed when I mastered the fill_between function. Specifically, using the where parameter for conditional shading and the alpha parameter for transparency.
Python Matplotlib fill_between Shading
The fill_between function in Python is designed to fill the area between two horizontal curves. It is an essential tool for showing variance, uncertainty, or specific regions of interest.
By default, Python fills the entire area between your Y-values. However, professional reports usually require more nuance, which is where the where logic and alpha transparency comes into play.
Python Matplotlib alpha Parameter for Transparency
The alpha parameter is a float value ranging from 0 (completely transparent) to 1 (completely opaque). In my experience, setting a high alpha often hides the grid lines or the actual data points.
I usually recommend an alpha value between 0.2 and 0.5. This allows the user to see the background grid while still clearly identifying the shaded region in the Python plot.
Method 1: Apply Global Alpha for Uniform Transparency in Python
When you want to shade an entire region under a curve, you apply a single alpha value. I use this frequently when plotting the S&P 500 performance to show the “area of growth” over time.
In the Python code below, I demonstrate how to shade the area under a line representing the US Gross Domestic Product (GDP) growth over a few quarters.
import matplotlib.pyplot as plt
import numpy as np
# Sample USA Economic Data: Quarters and GDP Growth (%)
quarters = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6']
gdp_growth = [2.1, 2.4, 1.9, 2.8, 3.2, 3.0]
# Convert quarters to numerical indices for plotting
x = np.arange(len(quarters))
y = np.array(gdp_growth)
plt.figure(figsize=(10, 6))
# Plotting the main line
plt.plot(x, y, color='blue', label='US GDP Growth %', linewidth=2)
# Using fill_between with the alpha parameter in Python
# We fill the area between the line and the x-axis (y=0)
plt.fill_between(x, y, color='skyblue', alpha=0.4)
plt.xticks(x, quarters)
plt.title('USA Quarterly GDP Growth Analysis (Python Matplotlib Alpha Example)')
plt.xlabel('Fiscal Quarters')
plt.ylabel('Growth Percentage')
plt.legend()
plt.grid(True, linestyle='--', alpha=0.6)
plt.show()I executed the above example code and added the screenshot below.

Method 2: Layer Multiple Shaded Regions with Different Python Alpha Values
Sometimes I need to compare two different datasets on the same Python plot, such as the stock prices of two major tech companies based in California.
By using different alpha levels, I can create an “overlap” effect. This makes it easy to see where the data points intersect without one color completely blocking the other.
import matplotlib.pyplot as plt
import numpy as np
# Mock Stock Data for Apple and Microsoft over 10 days
days = np.arange(1, 11)
apple_stock = [150, 152, 149, 155, 158, 160, 157, 159, 162, 165]
microsoft_stock = [280, 285, 282, 290, 295, 292, 288, 300, 305, 310]
plt.figure(figsize=(10, 6))
# Plotting both lines
plt.plot(days, apple_stock, color='green', label='Apple (AAPL)')
plt.plot(days, microsoft_stock, color='red', label='Microsoft (MSFT)')
# Filling with different alpha values to see overlaps
plt.fill_between(days, apple_stock, color='green', alpha=0.2)
plt.fill_between(days, microsoft_stock, color='red', alpha=0.2)
plt.title('Tech Giants Stock Price Comparison (Python Alpha Layering)')
plt.xlabel('Trading Days')
plt.ylabel('Price in USD')
plt.legend()
plt.show()I executed the above example code and added the screenshot below.

Python Matplotlib fill_between ‘where’ Parameter
The where parameter is perhaps the most useful feature for data analysts. It allows for conditional shading based on a logical statement.
I often use this to highlight “Danger Zones” or “Profit Zones.” For instance, if I am monitoring temperatures in New York City, I might want to shade only the days where the temperature exceeds 90°F.
Method 1: Conditional Shading Above or Below a Threshold in Python
This is my go-to method for highlighting specific events. The where parameter accepts a Boolean array, which tells Python exactly which pixels to fill and which to leave blank.
In the following Python example, we visualize the temperature in Chicago. We will highlight only the days where the temperature drops below freezing (32°F) using a red shade.
import matplotlib.pyplot as plt
import numpy as np
# Temperature data for a week in Chicago (Fahrenheit)
days = np.arange(1, 15)
temps = [35, 33, 30, 28, 25, 31, 34, 38, 40, 30, 27, 29, 33, 35]
freezing_point = 32
plt.figure(figsize=(10, 6))
plt.plot(days, temps, color='black', marker='o', label='Daily Temp')
plt.axhline(y=freezing_point, color='blue', linestyle='--', label='Freezing Point')
# Using the 'where' parameter to highlight sub-zero days in Python
plt.fill_between(days, temps, freezing_point,
where=(np.array(temps) < freezing_point),
color='red', alpha=0.5, interpolate=True, label='Danger Zone')
plt.title('Chicago Winter Temperatures (Python fill_between where Example)')
plt.xlabel('Day of the Month')
plt.ylabel('Temperature (°F)')
plt.legend()
plt.show()I executed the above example code and added the screenshot below.

Notice the interpolate=True argument. I always include this when using where. It ensures that the shading follows the line exactly between data points, preventing jagged edges.
Method 2: Highlight Intersections Between Two Curves in Python
A common task in financial modeling is identifying where one trend crosses another. In the US, we often look at the “Golden Cross” or “Death Cross” in stock moving averages.
By using two separate fill_between calls with opposite where conditions, I can shade the regions where Stock A is higher than Stock B in one color, and vice versa in another.
import matplotlib.pyplot as plt
import numpy as np
# Time frame: 20 days
x = np.linspace(0, 20, 100)
# Sine-wave style volatility for two US Retailers
retailer_a = 50 + 10 * np.sin(0.5 * x)
retailer_b = 50 + 10 * np.cos(0.5 * x)
plt.figure(figsize=(10, 6))
plt.plot(x, retailer_a, label='Retailer A Price', color='teal')
plt.plot(x, retailer_b, label='Retailer B Price', color='orange')
# Green fill where A > B
plt.fill_between(x, retailer_a, retailer_b, where=(retailer_a > retailer_b),
interpolate=True, color='green', alpha=0.3, label='A Outperforming B')
# Red fill where B > A
plt.fill_between(x, retailer_a, retailer_b, where=(retailer_b >= retailer_a),
interpolate=True, color='red', alpha=0.3, label='B Outperforming A')
plt.title('Comparative Market Performance (Python Conditional Shading)')
plt.xlabel('Time (Days)')
plt.ylabel('Market Value')
plt.legend(loc='upper right')
plt.show()I executed the above example code and added the screenshot below.

Using this method makes it incredibly easy for an executive to see at a glance who was winning the market share at any given time without looking at the raw numbers.
In my professional projects, I rarely use one without the other. If you use where without alpha, the colors are often too jarring and can distract from the trend line itself.
Conversely, using alpha without where means you are shading the whole area, which might hide the specific data points you want to emphasize. When I combine them, I create a “heat map” effect that guides the viewer’s eye to the most important parts of the graph.
Always remember that the goal of a Python visualization is to tell a story. If you are showing the rise of electric vehicle adoption in the United States, use a green alpha fill only where the numbers exceed the previous year’s average.
This level of detail is what separates a basic script from a high-level data analysis tool.
In this article, I have shown you how to use the Python Matplotlib fill_between function with the where and alpha parameters. We looked at how to control transparency to keep charts clean and how to use conditional logic to highlight specific data trends.
You may like to read:
- How to Use Matplotlib fill_between to Shade a Circle
- How to Make Y-Axis Tick Labels Invisible in Matplotlib
- Matplotlib Constrained_Layout vs Tight_Layout in Python
- Use tight_layout Colorbar and GridSpec in Matplotlib

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.