How to plot a continuous function with Python using Matplotlib and Seaborn?

In this tutorial we will show how to you can easily plot a function with Python and specifically using the Numpy, Matplotlib and Seaborn libraries.

Draw a continuous function graph with Python and Matplotlib

In this example we’ll going to go ahead and plot a function of two variables with Matplotlib. As an example, we’ll draw a simple line graph.

# import libraries
import matplotlib.pyplot as plt
import numpy as np'default')

# creating the test data
x = np.linspace(10, 100,10)

# rendering the chart

fig,ax= plt.subplots()'ggplot')
ax.set_title('My Chart')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis');

Code Steps

  1. We first import the Numpy and Matplotlib libraries.
  2. We’ll then use numpy functions numpy.linspace and np.power to quickly generate the line plot underlying data.
  3. Then, we use Matplotlib library to create a figure and a single plot area (referred in Matplotlib as axes), then render the graph itself using the plt.plot command.
  4. Las we customize our chart and assign a title and labels to the x and y axes.

Note that there are hundreds of possible customization that you can apply to our chart, whcih we covered in our other visualization tutorials.

Note II: In the same fashion you can draw other defined functions either piecewise and continuous (such as sine (using np.sin() , linear and so forth).


Plotting a continuous function plot with Seaborn

# using seaborn
import seaborn as sns
import numpy as np

# create data 
x = np.linspace(10, 100,10)

# draw the graph
fig,ax= plt.subplots()
ax = sns.lineplot(x=x, y=y)
ax.set_title('My Chart (using Seaborn)')
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis');


The code is quite similar to the one provided above. The main difference is the usage of the Seaborn library.

  1. Import Seaborn and Numpy.
  2. Definition of the dataset and continuous function X^3.
  3. Rendering the graph using the Seaborn sns.lineplot method.
  4. Some simple customizations to the chart (title and labels).