Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

Matplotlib.pyplot.fill() function in Python is a powerful tool for creating filled polygons in data visualization. This versatile function allows you to add color and depth to your plots, making them more visually appealing and informative. In this comprehensive guide, we’ll explore the Matplotlib.pyplot.fill() function in detail, covering its syntax, parameters, and various use cases. We’ll also provide numerous examples to help you master this essential plotting technique.

Understanding the Basics of Matplotlib.pyplot.fill()

The Matplotlib.pyplot.fill() function is part of the pyplot module in Matplotlib, a popular plotting library for Python. This function is used to create filled polygons by connecting a series of points with straight lines and filling the enclosed area with a specified color.

Let’s start with a simple example to demonstrate the basic usage of Matplotlib.pyplot.fill():

import matplotlib.pyplot as plt

x = [0, 1, 2, 1]
y = [0, 1, 0, -1]

plt.fill(x, y, 'r', alpha=0.5)
plt.title('Basic Matplotlib.pyplot.fill() Example - how2matplotlib.com')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

In this example, we create a simple diamond shape using four points. The Matplotlib.pyplot.fill() function takes the x and y coordinates as separate lists, followed by the color (‘r’ for red) and an optional alpha value for transparency. The resulting plot shows a filled red diamond with 50% opacity.

Syntax and Parameters of Matplotlib.pyplot.fill()

The Matplotlib.pyplot.fill() function has the following syntax:

matplotlib.pyplot.fill(*args, data=None, **kwargs)

Let’s break down the parameters:

  1. *args: These are alternating x and y coordinates of the polygon vertices. You can provide these as separate lists or as a single array-like object.

  2. data: This optional parameter can be used to specify a structured data object that contains the plotting data.

  3. **kwargs: These are additional keyword arguments that control various aspects of the fill, such as color, alpha, and line properties.

Some commonly used keyword arguments include:

  • color or c: Specifies the fill color
  • alpha: Sets the transparency (0 to 1)
  • edgecolor or ec: Sets the edge color of the polygon
  • linewidth or lw: Defines the width of the polygon’s edge
  • linestyle or ls: Sets the style of the polygon’s edge (e.g., solid, dashed, dotted)

Let’s see an example that demonstrates the use of these parameters:

import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0, 2*np.pi, 100)
r = 1 + 0.5 * np.sin(5*theta)
x = r * np.cos(theta)
y = r * np.sin(theta)

plt.fill(x, y, color='skyblue', alpha=0.7, edgecolor='navy', linewidth=2, linestyle='--')
plt.title('Matplotlib.pyplot.fill() with Custom Parameters - how2matplotlib.com')
plt.axis('equal')
plt.grid(True)
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

This example creates a more complex shape using polar coordinates. We use various keyword arguments to customize the appearance of the filled polygon, including color, alpha, edge color, line width, and line style.

Creating Multiple Filled Polygons

The Matplotlib.pyplot.fill() function allows you to create multiple filled polygons in a single call. This is particularly useful when you want to compare different datasets or create more complex visualizations.

Here’s an example that demonstrates how to create multiple filled polygons:

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.tan(x)

plt.fill(x, y1, 'r', alpha=0.3, label='sin(x)')
plt.fill(x, y2, 'g', alpha=0.3, label='cos(x)')
plt.fill(x, y3, 'b', alpha=0.3, label='tan(x)')

plt.title('Multiple Filled Polygons with Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.grid(True)
plt.ylim(-2, 2)
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

In this example, we create three filled polygons representing the sine, cosine, and tangent functions. Each polygon is filled with a different color and has a low alpha value to allow for overlapping. We also add labels to create a legend for better interpretation of the plot.

Using Matplotlib.pyplot.fill() with Pandas DataFrames

Matplotlib.pyplot.fill() can be easily integrated with Pandas DataFrames, making it a powerful tool for visualizing structured data. Let’s look at an example that demonstrates this integration:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Create a sample DataFrame
dates = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D')
data = {
    'Date': dates,
    'Value1': np.random.randn(len(dates)).cumsum(),
    'Value2': np.random.randn(len(dates)).cumsum()
}
df = pd.DataFrame(data)

plt.figure(figsize=(12, 6))
plt.fill(df['Date'], df['Value1'], 'r', alpha=0.3, label='Value1')
plt.fill(df['Date'], df['Value2'], 'b', alpha=0.3, label='Value2')

plt.title('Matplotlib.pyplot.fill() with Pandas DataFrame - how2matplotlib.com')
plt.xlabel('Date')
plt.ylabel('Cumulative Value')
plt.legend()
plt.grid(True)
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

This example creates a DataFrame with date and two random cumulative value columns. We then use Matplotlib.pyplot.fill() to create filled areas for both value columns, effectively visualizing their progression over time.

Creating Stacked Area Plots

Matplotlib.pyplot.fill() is particularly useful for creating stacked area plots, which are excellent for visualizing the composition of a whole over time. Let’s create a stacked area plot using this function:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.sin(x) + 0.5 * np.random.randn(100)
y3 = np.sin(x) + np.random.randn(100)

plt.fill_between(x, 0, y1, alpha=0.3, label='Layer 1')
plt.fill_between(x, y1, y1+y2, alpha=0.3, label='Layer 2')
plt.fill_between(x, y1+y2, y1+y2+y3, alpha=0.3, label='Layer 3')

plt.title('Stacked Area Plot using Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.grid(True)
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

In this example, we use plt.fill_between() (a variant of plt.fill()) to create a stacked area plot with three layers. Each layer is filled with a different color and stacked on top of the previous one, creating a visually appealing representation of the data composition.

Creating Filled Contour Plots

Matplotlib.pyplot.fill() can be used in conjunction with contour plots to create filled contour plots, which are useful for visualizing 3D data on a 2D plane. Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)

plt.figure(figsize=(10, 8))
contours = plt.contourf(X, Y, Z, levels=20, cmap='viridis')
plt.colorbar(contours)

plt.title('Filled Contour Plot using Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

This example creates a filled contour plot of a 2D sinusoidal function. The plt.contourf() function, which internally uses fill(), creates filled contours with a specified color map. We also add a colorbar to show the mapping between colors and values.

Creating Custom Shapes with Matplotlib.pyplot.fill()

Matplotlib.pyplot.fill() is not limited to simple polygons or predefined shapes. You can use it to create custom shapes by specifying the vertices of your desired polygon. Let’s create a custom star shape:

import matplotlib.pyplot as plt
import numpy as np

def create_star(outer_radius, inner_radius, num_points):
    angles = np.linspace(0, 2*np.pi, num_points, endpoint=False)
    x_outer = outer_radius * np.cos(angles)
    y_outer = outer_radius * np.sin(angles)
    x_inner = inner_radius * np.cos(angles + np.pi/num_points)
    y_inner = inner_radius * np.sin(angles + np.pi/num_points)
    x = np.empty((2*num_points,), dtype=float)
    y = np.empty((2*num_points,), dtype=float)
    x[0::2] = x_outer
    x[1::2] = x_inner
    y[0::2] = y_outer
    y[1::2] = y_inner
    return x, y

x, y = create_star(5, 2, 5)

plt.figure(figsize=(8, 8))
plt.fill(x, y, 'gold', edgecolor='darkgoldenrod', linewidth=2)
plt.title('Custom Star Shape using Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.axis('equal')
plt.grid(True)
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

In this example, we define a function to create the vertices of a star shape. We then use Matplotlib.pyplot.fill() to create a filled star with a gold color and dark golden rod edge.

Combining Matplotlib.pyplot.fill() with Other Plot Types

Matplotlib.pyplot.fill() can be combined with other plot types to create more complex visualizations. Let’s create a plot that combines a line plot with 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)

plt.plot(x, y1, 'r', label='sin(x)')
plt.plot(x, y2, 'b', label='cos(x)')
plt.fill_between(x, y1, 0, where=(y1>y2), interpolate=True, alpha=0.3, color='red')
plt.fill_between(x, y2, 0, where=(y2>y1), interpolate=True, alpha=0.3, color='blue')

plt.title('Combining Line Plots with Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.grid(True)
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

This example creates a plot with sine and cosine functions as line plots. We then use plt.fill_between() to fill the areas where each function is greater than the other, creating an interesting visual representation of their relationship.

Creating Gradient Fills with Matplotlib.pyplot.fill()

While Matplotlib.pyplot.fill() typically uses solid colors, you can create the illusion of a gradient fill by using multiple thin filled areas. Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(10, 6))
for i in range(100):
    alpha = 1 - i/100
    plt.fill_between(x, y-i*0.02, y-(i+1)*0.02, alpha=alpha, color='blue')

plt.title('Gradient Fill Effect using Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

In this example, we create multiple thin filled areas with decreasing alpha values to create a gradient effect. The result is a smooth transition from opaque to transparent, giving the illusion of a gradient fill.

Using Matplotlib.pyplot.fill() for Statistical Visualizations

Matplotlib.pyplot.fill() is particularly useful for statistical visualizations, such as creating confidence intervals or error bands. Let’s create a plot with a mean line and confidence interval:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x) + 0.1 * np.random.randn(100)
y_mean = np.sin(x)
y_std = 0.1 * np.ones_like(x)

plt.plot(x, y, 'b.', alpha=0.3, label='Data')
plt.plot(x, y_mean, 'r-', label='Mean')
plt.fill_between(x, y_mean - 2*y_std, y_mean + 2*y_std, alpha=0.3, color='gray', label='95% CI')

plt.title('Statistical Visualization with Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
plt.grid(True)
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

This example creates a scatter plot of noisy data points, a mean line, and a filled area representing the 95% confidence interval. The Matplotlib.pyplot.fill() function is used to create the shaded confidence interval.

Creating Filled Bar Plots with Matplotlib.pyplot.fill()

While Matplotlib provides a dedicated bar() function for creating bar plots, you can also use Matplotlib.pyplot.fill() to create custom filled bar plots. Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]

plt.figure(figsize=(10, 6))
for i, (cat, val) in enumerate(zip(categories, values)):
    plt.fill_between([i-0.4, i+0.4], [0, 0], [val, val], alpha=0.7)
    plt.text(i, val, str(val), ha='center', va='bottom')

plt.title('Custom Filled Bar Plot using Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.xticks(range(len(categories)), categories)
plt.grid(True, axis='y')
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

In this example, we use Matplotlib.pyplot.fill() to create custom filled bars for each category. We also add text labels on top of each bar to display the values.

Creating Pie Charts with Matplotlib.pyplot.fill()

While Matplotlib provides a pie() function for creating pie charts, you can also use Matplotlib.pyplot.fill() to create custom pie charts. Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

sizes = [30, 45, 25]
colors = ['red', 'green', 'blue']
labels = ['A', 'B', 'C']

plt.figure(figsize=(8, 8))
start_angle = 0
for size, color, label in zip(sizes, colors, labels):
    end_angle = start_angle + size * 3.6  # 3.6 degrees per 1%
    angles = np.linspace(start_angle, end_angle, 100)
    x = np.append(0, np.cos(np.radians(angles)))
    y = np.append(0, np.sin(np.radians(angles)))
    plt.fill(x, y, color=color, alpha=0.7)

    # Add labels
    midangle = np.mean([start_angle, end_angle])
    x = np.cos(np.radians(midangle)) * 0.5
    y = np.sin(np.radians(midangle)) * 0.5
    plt.text(x, y, f'{label}\n{size}%', ha='center', va='center')

    start_angle = end_angle

plt.title('Custom Pie Chart using Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.axis('equal')
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

In this example, we use Matplotlib.pyplot.fill() to create custom pie chart segments. We calculate the angles for each segment based on the sizes, and then use fill() to create the wedges. We also add labels to each segment.

Creating Heatmaps with Matplotlib.pyplot.fill()

While Matplotlib provides dedicated functions for creating heatmaps, you can use Matplotlib.pyplot.fill() to create custom heatmaps. Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(5, 5)
x, y = np.meshgrid(np.arange(data.shape[1]+1), np.arange(data.shape[0]+1))

plt.figure(figsize=(10, 8))
for i in range(data.shape[0]):
    for j in range(data.shape[1]):
        color = plt.cm.viridis(data[i, j])
        plt.fill([x[i,j], x[i,j+1], x[i+1,j+1], x[i+1,j]], 
                 [y[i,j], y[i,j+1], y[i+1,j+1], y[i+1,j]], 
                 color=color)
        plt.text(j+0.5, i+0.5, f'{data[i,j]:.2f}', 
                 ha='center', va='center')

plt.title('Custom Heatmap using Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.colorbar(plt.cm.ScalarMappable(cmap='viridis'))
plt.axis('equal')
plt.axis('off')
plt.show()

In this example, we use Matplotlib.pyplot.fill() to create individual cells of a heatmap. We color each cell based on its value using a colormap, and add text labels to display the values.

Creating Filled Violin Plots with Matplotlib.pyplot.fill()

Violin plots are a great way to visualize the distribution of data. While Matplotlib provides a violinplot() function, you can create custom violin plots using Matplotlib.pyplot.fill(). Here’s an example:

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

def violin_plot(ax, data, pos, bp=False):
    kde = stats.gaussian_kde(data)
    x = np.linspace(min(data), max(data), 100)
    y = kde(x)
    ax.fill_betweenx(x, pos, pos+y, alpha=0.3)
    ax.fill_betweenx(x, pos, pos-y, alpha=0.3)
    if bp:
        ax.boxplot(data, positions=[pos], widths=0.15)

np.random.seed(42)
data = [np.random.normal(0, std, 100) for std in range(1, 4)]

fig, ax = plt.subplots(figsize=(10, 6))
for i, d in enumerate(data):
    violin_plot(ax, d, i+1, bp=True)

ax.set_title('Custom Violin Plot using Matplotlib.pyplot.fill() - how2matplotlib.com')
ax.set_xlabel('Groups')
ax.set_ylabel('Values')
ax.set_xticks(range(1, len(data)+1))
ax.set_xticklabels([f'Group {i+1}' for i in range(len(data))])
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

In this example, we create a custom function to draw violin plots using Matplotlib.pyplot.fill(). We use fill_betweenx() (a variant of fill()) to create the violin shape, and optionally add a box plot for additional statistical information.

Creating Filled Radar Charts with Matplotlib.pyplot.fill()

Radar charts (also known as spider charts or star charts) are useful for displaying multivariate data. Let’s create a filled radar chart using Matplotlib.pyplot.fill():

import matplotlib.pyplot as plt
import numpy as np

categories = ['A', 'B', 'C', 'D', 'E', 'F']
values = [4, 3, 5, 2, 4, 3]

angles = np.linspace(0, 2*np.pi, len(categories), endpoint=False)
values = np.concatenate((values, [values[0]]))  # repeat the first value to close the polygon
angles = np.concatenate((angles, [angles[0]]))  # repeat the first angle to close the polygon

fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(projection='polar'))
ax.fill(angles, values, alpha=0.25)
ax.plot(angles, values)

ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories)
ax.set_title('Filled Radar Chart using Matplotlib.pyplot.fill() - how2matplotlib.com')
plt.show()

Output:

Comprehensive Guide to Matplotlib.pyplot.fill() Function in Python

In this example, we create a radar chart by using a polar projection and filling the area enclosed by the data points. The Matplotlib.pyplot.fill() function is used to create the filled area, while plot() is used to draw the outline.

Creating Filled Stream Graphs with Matplotlib.pyplot.fill()

Stream graphs are a variation of stacked area graphs where the baseline is free to move. They can be created using Matplotlib.pyplot.fill(). Here’s an example:

import matplotlib.pyplot as plt
import numpy as np

def stream_graph(x, ys, colors, labels):
    ys = np.row_stack(ys)
    baseline = ys.sum(axis=0) / 2

    fig, ax = plt.subplots(figsize=(12, 6))
    for i, (y, color, label) in enumerate(zip(ys, colors, labels)):
        ax.fill_between(x, baseline - y/2, baseline + y/2, color=color, alpha=0.7, label=label)
        baseline += y

    ax.set_title('Stream Graph using Matplotlib.pyplot.fill() - how2matplotlib.com')
    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.tight_layout()
    plt.show()

x = np.linspace(0, 10, 100)
y1 = np.sin(x) + 1
y2 = np.cos(x) + 1
y3 = np.tan(x) + 1

stream_graph(x, [y1, y2, y3], ['red', 'green', 'blue'], ['Sin', 'Cos', 'Tan'])

In this example, we create a custom function to draw a stream graph using Matplotlib.pyplot.fill_between(). The baseline for each stream is calculated based on the values of all streams, creating the characteristic flowing appearance of a stream graph.

Conclusion

The Matplotlib.pyplot.fill() function is a versatile tool in the data visualization toolkit. From simple filled polygons to complex statistical visualizations, this function offers a wide range of possibilities for creating informative and visually appealing plots.

Throughout this comprehensive guide, we’ve explored various applications of Matplotlib.pyplot.fill(), including:

  1. Basic usage and syntax
  2. Creating multiple filled polygons
  3. Integration with Pandas DataFrames
  4. Stacked area plots
  5. Filled contour plots
  6. Custom shapes
  7. Combination with other plot types
  8. Gradient fill effects
  9. Statistical visualizations
  10. Custom filled bar plots
  11. Custom pie charts
  12. Custom heatmaps
  13. Filled violin plots
  14. Filled radar charts
  15. Stream graphs
Like(0)

Matplotlib Articles