Getting Started With Matplotlib Using Python

Matplotlib is a multi-platform library for data visualization built on top of NumPy arrays. It works very well with all the operating systems and supports many output types and backend systems.

Before we begin with Matplotlib, we need to pull in the required package.

Required Package

We need to install matplotlib and that can be done using the below code:

pip install matplotlib

Once this is installed we are good to go ahead and import it along with numpy as shown below:

import matplotlib.pyplot as plt
import numpy as np

Create Simple Line Plot

To create a sample line plot, we can go ahead and use sin(…) with some randomly generated values using linspace(…):

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

linspace(…) will create an array of 100 values spaced between 1 and

Once values are generated, we can show out plot as shown below:

plt.plot(x, np.sin(x), ‘-’)
plt.show()

On executing this, you will see the below plot,

If you want to plot multiple curves together, you can add another plot statement as shown below:

plt.plot(x, np.sin(x), ‘-’)
plt.plot(x, np.cos(x), ‘o’)

The above two statements will generate the output as,

Save Plot

In order to save the plot, we need to create a container that will hold all visualization related data, including axis, input values, legends, etc. This container is called figure and we can create a figure as shown below:

fig = plt.figure()

Here is the complete code to create and save plot having description and legends:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig = plt.figure()
plt.title(“Sample Curves”)
plt.xlabel(“x label”)
plt.ylabel(“y label”)
plt.plot(x, np.sin(x), ‘-g’, label=’sin(x)’)
plt.plot(x, np.cos(x), ‘:b’, label=’cos(x)’)
plt.legend()
fig.savefig(‘MyPlot.png’)

On executing the above code, you can see that the file named MyPlot.png is generated in your current directory. Here is the gist of how the plot looks like,

Hope you enjoyed creating basic plots to get started with Matplotlib library. I’ve created few videos demonstrating some more points related to plots on my YouTube channel. Make sure to check those out here.


Similar Articles