Matplotlib - Area Plots



An area plot is like a line graph, but instead of just showing the lines, it fills the space below them with colors. It is a type of data visualization that displays quantitative data using shaded areas to represent different categories or groups over a continuous range.

Imagine you have data that changes over time, like sales for different products. An area plot is a way to show how much each product contributes to the total sales at each point in time. It uses shaded areas to represent each product, and when you stack them together, you get a visual picture of how they add up over time.

Area Plots

Area Plots in Matplotlib

In Matplotlib, we can create an area plot using the fill_between() function or the stackplot() function. These functions allows us to customize colors, transparency, and labels to enhance the visual representation of the data.

The fill_between() Function

The fill_between() function shades the area between two specified curves. It is commonly used to highlight specific areas of interest in a plot.

Syntax

Following is the syntax of fill_between() function in Matplotlib −

fill_between(x, y1, y2=0, where=None, interpolate=False, step=None, **kwargs)

Where,

  • x is the x-coordinates of the data points.
  • y1 is the y-coordinates of the first curve.
  • y2 is the y-coordinates of the second curve or the baseline. If not specified, it defaults to 0, creating a fill between the curve and the x-axis.
  • where is an optional condition to limit the filling. If provided, only the regions where the condition is True will be filled.
  • If interpolate is True, the filled area will be interpolated. If False (default), steps are used to create stairs-like filling.
  • If step is not None, it defines the step type to use for interpolation (plotting). Possible values are 'pre', 'post', or 'mid'.
  • **kwargs is the additional keyword arguments that control the appearance of the filled region, such as color, alpha, label, etc.

Example

In the following example, we are filling the area between the curves y=x2 and y=x with a sky-blue color, and using the alpha parameter to control the transparency of the filled region. We are then passing label argument to add a legend to the plot −

import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
x = np.linspace(0, 5, 100)
y1 = x**2
y2 = x

# Fill the region between y1 and y2 with a sky-blue color and set transparency
plt.fill_between(x, y1, y2, color='skyblue', alpha=0.4, label='Filled Area')

# Plot the curves for y=x^2 and y=x
plt.plot(x, y1, label='y=x^2')
plt.plot(x, y2, label='y=x')

# Add labels to the axes
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Add a title to the plot
plt.title('Fill Between Example')
# Add a legend to identify the filled area and the curves
plt.legend()
# Show the plot
plt.show()

Output

Following is the output of the above code −

Basic Area Plot

The stackplot() Function

The stackplot() function is used to create a stacked area plots. It allows you to represent the cumulative contribution of multiple datasets or categories to a whole over a continuous range. Each category is represented by a filled area, and the combined areas give an overview of the overall trend.

Syntax

Following is the syntax of stackplot() function in Matplotlib −

stackplot(x, *args, labels=(), colors=None, baseline='zero', alpha=1, **kwargs)

Where,

  • x is the x-coordinates of the data points.
  • *args is the variable-length argument list of y-coordinates for each dataset or category to be stacked.
  • labels is a tuple or list of labels for each dataset, used for creating a legend.
  • colors is a tuple or list of colors for each dataset. If not specified, Matplotlib will automatically choose colors.
  • baseline specifies whether stacking is relative to 'zero' (default) or 'sym' (symmetric around zero).
  • alpha specifies the transparency of the filled areas.
  • **kwargs is the additional keyword arguments that control the appearance of the filled region, such as color, alpha, label, etc.

Example

In here, we are using the stackplot() function to create a visual representation of three datasets 'y1', 'y2' and'y3' stacked on top of each other. The legend helps identify each dataset in the plot and the transparency effect enhances the visualization of the filled areas −

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.exp(-0.1 * x) * np.sin(x)
# Create a stacked area plot
plt.stackplot(x, y1, y2, y3, labels=['Sin(x)', 'Cos(x)', 'Exp(-0.1*x)*Sin(x)'], alpha=0.7)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Stacked Area Plot Example')
plt.legend()
plt.show()

Output

After executing the above code, we get the following output −

Stack Plot

Gradient-Filled Area Plot

A gradient-filled area plot is like coloring the space under a curve with a smooth transition of colors. It helps emphasize the shape of the curve and how it changes.

Example

In the following example, we are creating a smooth curve representing the sine function using numpy. We are then using the fill_between() function to fill the area under the curve with a gradient, starting from the x-axis up to the curve −

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.fill_between(x, y, color='purple', interpolate=True)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Gradient-Filled Area Plot')
plt.show()

Output

The resulting plot shows a gradual color transition under the curve −

Gradient-Filled Area Plot

Percentage Stacked Area Plot

A percentage stacked area plot refers to visualizing different parts of a whole over time, where each part is shown as a percentage contribution to the total. It helps to understand how the proportions of various components change relative to the entire set.

Example

In here, we are representing the percentage contribution of various energy sources (such as coal, natural gas, renewable energy, and nuclear) to the overall energy consumption in a country over several years −

import matplotlib.pyplot as plt

years = [2010, 2012, 2014, 2016, 2018]
# Percentage contribution of coal to total energy consumption
coal = [40, 35, 30, 25, 20]
# Percentage contribution of natural gas
natural_gas = [30, 25, 20, 18, 15]
# Percentage contribution of renewable energy
renewable_energy = [15, 20, 25, 30, 35]
# Percentage contribution of nuclear energy
nuclear = [15, 20, 25, 27, 30]  

plt.stackplot(years, coal, natural_gas, renewable_energy, nuclear,
              labels=['Coal', 'Natural Gas', 'Renewable Energy', 'Nuclear'],
              colors=['#1f78b4', '#33a02c', '#a6cee3', '#fdbf6f'],
              alpha=0.7, baseline='zero')

plt.xlabel('Years')
plt.ylabel('Percentage of Total Energy Consumption')
plt.title('Energy Source Composition Over Time')
plt.legend(loc='upper left')
plt.show()

Output

The output obtained is as shown below −

Percentage Stacked Area Plot

Area Plot with Annotations

An area plot with annotations allows you to add textual or graphical elements to the plot, highlighting specific points or regions on it. It provides additional information about significant data points or regions. These annotations can include labels, arrows, or other markers to draw attention to specific area of interest.

Example

In here, we are determining monthly sales data with a light blue filled area, representing the sales trend. We are adding annotations to highlight significant points on the plot, such as a sales peak and the month with the lowest sales. The annotate() function is used to position text and arrows at specific locations −

import numpy as np
import matplotlib.pyplot as plt

# Simulating monthly sales data
months = np.arange(1, 13)
sales = np.array([10, 15, 12, 18, 25, 30, 28, 35, 32, 28, 20, 15])

# Create an area plot
plt.fill_between(months, sales, color='lightblue', alpha=0.7, label='Monthly Sales')

# Add annotations for significant points
plt.annotate('Sales Peak', xy=(5, 30), xytext=(6, 32),
             arrowprops=dict(facecolor='black', shrink=0.05),
             fontsize=8, ha='center')

plt.annotate('Lowest Sales', xy=(11, 15), xytext=(10, 18),
             arrowprops=dict(facecolor='black', shrink=0.05),
             fontsize=8, ha='center')

# Add labels and title
plt.xlabel('Months')
plt.ylabel('Sales (in units)')
plt.title('Monthly Sales Trend with Annotations')

# Show the plot
plt.legend()
plt.show()

Output

The output obtained is as shown below −

Area Plot with Annotations
Advertisements