Simple Line Plot with Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This tutorial demonstrates how to use Python's Matplotlib library to create a simple line plot with a shaded region representing the area under the curve. The plot includes a text label, axis labels, and custom tick placement and labels.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/line_plots -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/booleans -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/lists -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/tuples -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/sets -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/function_definition -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/importing_modules -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/using_packages -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/numerical_computing -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/data_visualization -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} python/build_in_functions -.-> lab-48788{{"`Simple Line Plot with Matplotlib`"}} end

Define the function

First, define the function that will be plotted. In this example, the function is (x - 3) _ (x - 5) _ (x - 7) + 85.

def func(x):
    return (x - 3) * (x - 5) * (x - 7) + 85

Define the integral limits

Next, define the limits of the integral. In this example, the limits are a = 2 and b = 9.

a, b = 2, 9

Create the x and y values

Generate a range of x values using the numpy linspace function. Then, use the function defined in step 1 to generate the corresponding y values.

import numpy as np

x = np.linspace(0, 10)
y = func(x)

Create the plot

Create a figure and axis object using subplots. Plot the x and y values using plot. Set the y-axis limits to start at 0 using set_ylim.

fig, ax = plt.subplots()
ax.plot(x, y, 'r', linewidth=2)
ax.set_ylim(bottom=0)

Create the shaded region

Create the shaded region using a Polygon patch. Generate x and y values for the region using linspace and the function defined in step 1. Then, define the vertices of the region as a list of tuples. Finally, create the Polygon object and add it to the axis using add_patch.

from matplotlib.patches import Polygon

ix = np.linspace(a, b)
iy = func(ix)
verts = [(a, 0), *zip(ix, iy), (b, 0)]
poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')
ax.add_patch(poly)

Add the integral label

Add the integral label to the plot using text. The label should be centered at the midpoint between a and b and should be formatted using mathtext.

ax.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$",
        horizontalalignment='center', fontsize=20)

Add axis labels and tick labels

Add the x and y-axis labels using figtext. Hide the top and right spines using spines. Set custom tick placement and labels using set_xticks and set_yticks.

fig.text(0.9, 0.05, '$x$')
fig.text(0.1, 0.9, '$y$')

ax.spines[['top', 'right']].set_visible(False)
ax.set_xticks([a, b], labels=['$a$', '$b$'])
ax.set_yticks([])

Show the plot

Use show to display the plot.

plt.show()

Summary

This tutorial demonstrated how to use Python's Matplotlib library to create a simple line plot with a shaded region representing the area under the curve. The plot included a text label, axis labels, and custom tick placement and labels. By following the steps outlined in this tutorial, you can create similar plots for your own data.

Other Python Tutorials you may like