Area line plots are an effective tool in the data visualization toolbox for illustrating relationships and trends across time. They provide a comprehensive and visually captivating method of presenting numerical data by expertly combining the readability of line charts with the eye-catching attractiveness of filled areas.
In this article, we will learn more about creating an area line chart in Python. As Area line plots offer a valuable tool for data visualization, providing a clear and engaging way to convey trends and relationships over time.
What is an Area Line Plot?
An Area Line Plot, also known as an Area Chart or Stacked Area Chart, is a data visualization technique that is used to represent data over time or across categories. It is an extension of the basic line chart and is particularly useful when you want to show the composition of a whole, along with the individual components, as well as how they change over time or across categories. In this article, we will explore how to create area line plots in Python using the matplotlib
library and explain their significance in visualizing data.
Here are the key components and characteristics of an Area Line Plot.
X-Axis: The horizontal axis represents the independent variable, typically time or categories. It is a continuous or categorical scale that provides context for the data points.
Y-Axis: The vertical axis represents the dependent variable, usually a numeric value that measures the quantity or magnitude of what you are visualizing.
Lines: The individual lines in an area line plot represent different categories, groups, or components. Each line starts at the baseline (usually the X-axis) and goes up to show the value of that category or component at a particular point in time or along the category axis.
Area Filling: The area between the line and the baseline is filled with colour to make it visually distinct. The area's colour is often used to represent the category or component it represents.
Stacking: In a stacked area chart, each line is stacked on top of the previous one. This stacking illustrates how the total changes over time or across categories, as well as the contribution of each category to the whole.
Creating an Area Line Plot
First, let's make a basic area line plot using Python. To create the plot and show how various categories change over time, we will use Matplotlib.
Python3
import pandas as pd
import matplotlib.pyplot as plt
# Sample data
df = pd.DataFrame({
'x': list(range(1, 11)),
'y': [1, 3, 2, 4, 5, 7, 6, 8, 9, 10]
})
# Create the area line plot
plt.fill_between(df['x'], df['y'], color='blue', alpha=0.2)
plt.plot(df['x'], df['y'], color='red', alpha=0.5, linewidth=0.9)
plt.title("Area Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Output:
Area line PlotArea Line Plot with markers and Labels
Add some more function to make it attractive
- Import necessary libraries: pandas for data manipulation and matplotlib.pyplot for data visualization.
- Prepare sample data: Create a DataFrame with columns for 'x' and 'y' containing numerical values.
- Generate area line plot: Use plt.fill_between() to create a semi-transparent blue area line plot and plt.plot() to create a faint red line.
- Enhance plot with markers and labels: Add red circular markers (s=30) at data points using plt.scatter(). Add black labels above each data point using plt.text(), positioning them horizontally centered (ha='center') and vertically aligned at the bottom (va='bottom'). Customize axes, add title, and display the plot.
Python3
import pandas as pd
import matplotlib.pyplot as plt
# Sample data
df = pd.DataFrame({
'x': list(range(1, 11)),
'y': [1, 3, 2, 4, 5, 7, 6, 8, 9, 10]
})
# Create the area line plot
plt.fill_between(df['x'], df['y'], color='blue', alpha=0.5)
plt.plot(df['x'], df['y'], color='red', alpha=0.1)
# Add red markers at data points
plt.scatter(df['x'], df['y'], color='red', s=30)
# Add labels above data points
for i, row in df.iterrows():
plt.text(row['x'], row['y'], str(row['y']), ha='center', va='bottom', color='black', size=10)
plt.title("Area Line Plot with Markers and Labels")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Output:
Area Line PlotStacked Area Line Plot
- Import necessary libraries: pandas for data manipulation and matplotlib.pyplot for data visualization.
- Prepare sample data: Create a DataFrame with columns for 'x', 'Category A', 'Category B', and 'Category C' containing numerical values.
- Define custom colors: Define a list of colors ('yellow', 'purple', 'pink') to be used for each category.
- Generate stacked area line plot: Use plt.stackplot() to create a stacked area line plot with the defined colors and transparency. Additionally, plot individual lines for each category with different colors, linewidths, and transparency. Add labels, customize axes, and display the plot.
Python3
import pandas as pd
import matplotlib.pyplot as plt
# Sample data
df = pd.DataFrame({
'x': list(range(1, 11)),
'Category A': [1, 3, 2, 4, 5, 7, 6, 8, 9, 10],
'Category B': [2, 4, 3, 5, 6, 8, 7, 9, 10, 11],
'Category C': [3, 5, 4, 6, 7, 9, 8, 10, 11, 12]
})
# Define custom colors for each category
colors = ['yellow', 'purple', 'pink']
# Create the stacked area line plot with custom colors
plt.stackplot(df['x'], df['Category A'], df['Category B'], df['Category C'], colors=colors, alpha=0.7)
# Plot lines for each category with custom colors
plt.plot(df['x'], df['Category A'], color='blue', alpha=0.5, linewidth=0.9)
plt.plot(df['x'], df['Category B'], color='green', alpha=0.5, linewidth=0.9)
plt.plot(df['x'], df['Category C'], color='red', alpha=0.5, linewidth=0.9)
plt.title("Stacked Area Line Plot with Custom Colors")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()
Output:

Filling between lines
- Import necessary libraries: matplotlib.pyplot for data visualization and numpy for numerical operations.
- Prepare sample data: Generate x-axis values using np.linspace and calculate corresponding y-values using sin and cos functions.
- Create plot elements: Create a figure and axis using plt.subplots() and plot two lines using ax.plot() with different colors and labels.
- Fill between lines: Use ax.fill_between() to fill the area between the lines with a specific color and transparency, applying conditions and interpolation. Add labels, customize axes, and display the plot.
Python3
import matplotlib.pyplot as plt
import numpy as np
# Sample data for demonstration
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create a figure and axis
fig, ax = plt.subplots()
# Plot the two lines
ax.plot(x, y1, label='Line 1', color='blue')
ax.plot(x, y2, label='Line 2', color='green')
# Fill the area between the lines
ax.fill_between(x, y1, y2, where=(y1 > y2), interpolate=True, alpha=0.5, color='yellow', label='Fill Area')
# Customize the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_title('Filling Between Lines')
ax.legend()
# Display the plot
plt.show()
Output:

Area Line plot with Plotly
- Import essential libraries: Plotly Express for creating charts and Pandas for data manipulation.
- Prepare sample data: Create a DataFrame with 'x' and 'y' columns containing integer values.
- Generate area line plot: Use px.area() to create an area line plot with fill-to-zero, linear line shape, and green line color.
- Customize layout: Add title, axis labels, and hide legend using update_layout().
Python3
import plotly.graph_objects as go
import pandas as pd
# Sample data
df = pd.DataFrame({
'x': list(range(1, 11)),
'y': [1, 3, 2, 4, 5, 7, 6, 8, 9, 10]
})
# Create the Area Line Plot
fig = go.Figure(data=go.Scatter(x=df['x'], y=df['y'], fill='tozeroy', mode='lines', line=dict(color='green')))
fig.update_layout(
title="Area Line Plot with Plotly",
xaxis_title="X-axis",
yaxis_title="Y-axis",
showlegend=False # Hide legend
)
fig.show()
Output:

Conclusion
In summary, area line plots are effective for displaying trends, comparisons, and part-to-whole relationships in data over time or across categories. They provide a visually compelling way to understand how different components contribute to the whole and how these contributions change over the chosen axis (time or categories).
Similar Reads
Python - Data visualization tutorial Data visualization is a crucial aspect of data analysis, helping to transform analyzed data into meaningful insights through graphical representations. This comprehensive tutorial will guide you through the fundamentals of data visualization using Python. We'll explore various libraries, including M
7 min read
What is Data Visualization and Why is It Important? Data visualization uses charts, graphs and maps to present information clearly and simply. It turns complex data into visuals that are easy to understand.With large amounts of data in every industry, visualization helps spot patterns and trends quickly, leading to faster and smarter decisions.Common
4 min read
Data Visualization using Matplotlib in Python Matplotlib is a widely-used Python library used for creating static, animated and interactive data visualizations. It is built on the top of NumPy and it can easily handles large datasets for creating various types of plots such as line charts, bar charts, scatter plots, etc. Visualizing Data with P
11 min read
Data Visualization with Seaborn - Python Seaborn is a popular Python library for creating attractive statistical visualizations. Built on Matplotlib and integrated with Pandas, it simplifies complex plots like line charts, heatmaps and violin plots with minimal code.Creating Plots with SeabornSeaborn makes it easy to create clear and infor
9 min read
Data Visualization with Pandas Pandas is a powerful open-source data analysis and manipulation library for Python. The library is particularly well-suited for handling labeled data such as tables with rows and columns. Pandas allows to create various graphs directly from your data using built-in functions. This tutorial covers Pa
6 min read
Plotly for Data Visualization in Python Plotly is an open-source Python library designed to create interactive, visually appealing charts and graphs. It helps users to explore data through features like zooming, additional details and clicking for deeper insights. It handles the interactivity with JavaScript behind the scenes so that we c
12 min read
Data Visualization using Plotnine and ggplot2 in Python Plotnine is a Python data visualization library built on the principles of the Grammar of Graphics, the same philosophy that powers ggplot2 in R. It allows users to create complex plots by layering components such as data, aesthetics and geometric objects.Installing Plotnine in PythonThe plotnine is
6 min read
Introduction to Altair in Python Altair is a declarative statistical visualization library in Python, designed to make it easy to create clear and informative graphics with minimal code. Built on top of Vega-Lite, Altair focuses on simplicity, readability and efficiency, making it a favorite among data scientists and analysts.Why U
4 min read
Python - Data visualization using Bokeh Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like notebook, html and server. It is possible to embed bokeh plots in Django and flask apps. Bokeh provides two visualization interfaces to us
4 min read
Pygal Introduction Python has become one of the most popular programming languages for data science because of its vast collection of libraries. In data science, data visualization plays a crucial role that helps us to make it easier to identify trends, patterns, and outliers in large data sets. Pygal is best suited f
5 min read