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

plt.style.use('default')

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

# rendering the chart

fig,ax= plt.subplots()
plt.style.use('ggplot')
ax.plot(x,y);
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).

Chart

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)
y=np.power(x,3)

# draw the graph
sns.set_style('dark')
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');

Steps

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).

Chart