# Matplotlib Plot NumPy Array

In this Python Matplotlib tutorial, we will discuss Matplotlib plot numpy array in matplotlib. Here we will cover different examples related to plot numpy array using matplotlib. And we will also cover the following topics:

• Matplotlib plot numpy array
• Matplotlib plot numpy array as line
• Matplotlib scatter plot numpy array
• Matplotlib plot multiple lines from numpy array
• Python plot numpy array as heatmap
• Matplotlib plot numpy array as image
• Matplotlib save plot to numpy array
• Matplotlib plot numpy array 2d
• Matplotlib plot numpy array 3d
• Matplotlib plot numpy matrix
• Matplotlib plot numpy array columns

## Matplotlib plot numpy array

In Python, matplotlib is a plotting library. We can use it along with the NumPy library of Python also. NumPy stands for Numerical Python and it is used for working with arrays.

The following are the steps used to plot the numpy array:

• Defining Libraries: Import the required libraries such as matplotlib.pyplot for data visualization and numpy for creating numpy array.
• Define Data: Define x-axis and y-axis data coordinates that are used for plotting.
• Plot the chart: By using the plot(), scatter() methods of the matplotlib library we can draw the chart.
• Visualize a Plot: By using the show() method users can generate a plot on their screen.

Let’s see an example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Data Cooedinates

x = np.arange(5, 10)
y = np.arange(12, 17)

# PLot

plt.plot(x,y)

plt.title("Matplotlib PLot NumPy Array")

plt.xlabel("x axis")
plt.ylabel("y axis")

# Display

plt.show()``````

Explanation:

• Import the required libraries such as matplotlib.pyplot, and numpy.
• After this, we define data coordinates using the np.arange() function of numpy.
• To plot the graph, use the plot() function of matplotlib.
• Then we add title and labels at the axes of the plot, using title(), xlabel(), and ylabel() method.

Output:

Also, check: Matplotlib set_xticks

## Matplotlib plot numpy array as line

We’ll learn to create a line graph using the numpy function. For this, we use the np.arange() function which returns equally spaced values from the interval.

Let’s see an example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Data Coordinates

x = np.arange(2, 8)
y = np.array([5, 8, 6, 20, 18, 30])

# PLot

plt.plot(x, y, linestyle='--')

plt.title("Matplotlib Plot NumPy Array As Line")

plt.xlabel("x axis")
plt.ylabel("y axis")

# Display

plt.show()``````
• In this example, to define data coordinates, we use arange() and array() method of numpy.
• To plot the line graph, use the plot() method and we also pass linestyle parameter to the method to change the style of a line.
• To add a title to the plot, use the title() function.
• To add labels at the x and y axes of the plot, use the xlabel() and ylabel() method.

## Matplotlib scatter plot numpy array

We’ll learn to create a scatter graph using the numpy function.

Let’s see an example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Data Coordinates

x = np.arange(2, 8)
y = x * 2 + 6

# Plot

plt.scatter(x, y)

plt.title("Matplotlib Scatter Plot NumPy Array")

plt.xlabel("x axis")
plt.ylabel("y axis")

# Display

plt.show()``````
• In the above example, we create a ndarray on the x-axis using the np.arange() function and on the y-axis, we create a ndarray using equation.
• To plot a scatter graph, use the scatter() method.

## Matplotlib plot multiple lines from numpy array

We’ll learn to plot multiple lines from a numpy array.

Example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Data Coordinates

x = np.arange(2, 8)
y1 = x * 3
y2 = np.array([5, 2.6, 4, 15, 20, 6])

# PLot

plt.plot(x, y1)
plt.plot(x, y2)

plt.title("Matplotlib Multiple Line Plot From NumPy Array")

plt.xlabel("x axis")
plt.ylabel("y axis")

# Display

plt.show()``````

Output:

• In the above example, we define x, y1, and y2 data coordinates.
• After this, we plot a graph between(x,y1) and (x,y2) using plot() method of matplotlib.

## Python plot numpy array as heatmap

Heatmap is a data visualization graphical technique in which we represent data using colors to visualize the value of the matrix. Heatmap is also known as a shading matrix.

There are different ways to plot Heatmap as a numpy array:

• Using matplotlib imshow() function
• Using matplotlib pcolormesh() function
• Using seaborn heatmap() function

### Using matplotlib imshow() function

The imshow() function of matplotlib is used to display data as an image.

The following is the syntax:

``````matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None,
interpolation=None, alpha=None,
vmin=None, vmax=None, origin=None,
extent=None, shape=, filternorm=1,
url=None, \* , data=None, \*\*kwargs)
``````

Example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(100).reshape((10,10))

# Heat map

plt.imshow( x, cmap = 'rainbow' , interpolation = 'bilinear')

plt.title( "Heat Map" )

# Display

plt.show()``````
• Here we use the arange() method of numpy to define data coordinate.
• After this, we use the imshow() function to plot the heatmaps. We pass the x parameter to represent data of the image, the cmap parameter is the colormap instance, and the interpolation parameter is used to display an image.

### Using matplotlib pcolormesh() function

The pcolormesh() function is used to create a pseudocolor plot with a non-regular rectangular grid.

The following is the syntax:

``````matplotlib.pyplot.pcolormesh(*args, alpha=None, norm=None,
cmap=None, vmin=None, vmax=None,
data=None, **kwargs)``````

Example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(10000).reshape((100,100))

# Heat map

plt.pcolormesh( x, cmap = 'coolwarm')

plt.title( "Heat Map" )

# Display

plt.show()``````

### Using seaborn heatmap() function

The heatmap() function is used to plot rectangular data as a color matrix.

The following is the syntax:

``````seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None,
center=None, annot_kws=None, linewidths=0,
linecolor='white', cbar=True, **kwargs)``````

Example:

``````# Import Library

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# Define Data Coordinates

x = np.arange(15**2).reshape((15, 15))

# HeatMap

sns.heatmap( x , linewidth = 0.5 , cmap = 'Dark2' )

plt.title( "Heat Map" )

# Display

plt.show()``````
• In the above example, we import numpy, matplotlib.pyplot, and seaborn library.
• After this, we define data coordinates using arange() method of numpy and reshape it using reshape() method.
• Then we use the heatmap() function of the seaborn.
• To add a title to the plot, use the title() function.

## Matplotlib plot numpy array as image

We’ll learn to plot the numpy array as an image. We use the matplotlib.pyplot.imshow() function to convert a numpy array ta an image.

Let’s see an example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.array([[[0, 0, 128], [255, 255, 0], [128, 0, 0]],
[[0, 255, 0], [0, 0, 255], [255, 0, 255]]])

# Image

plt.imshow(x)

# Display

plt.show()``````
• In the above example, we import matplotlib.pyplot and numpy library.
• Next, we define an array of RGB color codes.
• Then we use the imshow() function to save the array as an image.

## Matplotlib save plot to numpy array

We’ll learn to plot numpy arrays. To save a plot use the savefig() function of matplotlib pyplot module.

Let’s see an example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.array([1, 2.5, 8, 4.3, 6])

# Plot

plt.plot(x)

# Save

plt.savefig('NumPy Array.png')

# Display

plt.show()``````
• Here we define data coordinate using the array() method of numpy and to plot the data we, use the plot() method.
• To save the plot as a png image, we use the savefig() method.

## Matplotlib plot numpy array 2d

We’ll learn to plot 2d numpy array using plot() method of pyplot module of matplotlib.

Example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.array([[2, 4, 6], [6, 8, 10]])
y = np.array([[8, 10, 12], [14, 16, 18]])

# Plot

plt.plot(x, y)

# Display

plt.show()``````
• Here we create 2d array to define data coordinates x and y.
• To plot the 2D numpy array, use the plot() method.

## Matplotlib plot numpy array 3d

We’ll learn to plot 3d numpy array using the scatter method of the axes module of matplotlib. We also use the 3d projection to create a 3d plot.

Example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Create figure and subplot

fig = plt.figure()

# Define Data

x = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
y = np.array([[[1, 2, 3], [4, 5, 6]], [[8, 10, 12], [4, 5, 6]]])
z = np.array([[[5, 6, 9], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

# Plot

ax.scatter(x, y, z, color='red')

# Display

plt.show()``````

The following are the steps to create a 3D plot from a 3D numpy array:

• Import libraries first, such as numpy and matplotlib.pyplot
• Create a new using figure() method.
• Create a 3D numpy array using array() method of numpy.
• Plot 3D plot using scatter() method.
• To display the plot, use show() method.

## Matplotlib plot numpy matrix

We’ll learn to plot a numpy matrix. Numpy matrices are strictly 2-dimensional. To display an array as a matrix we use the matshow() method of pyplot module of matplotlib.

Example #1

``````# Import Library

import matplotlib.pyplot as plt
import numpy as np

# Function

def mat (dim):
x = np.zeros(dim)
for i in range(max(dim)):
x[i, i] = -i
return x

# Display matrix

plt.matshow(mat((20,20)))

# Display

plt.show()``````
• Firstly, we import matplotlib.pyplot and numpy library.
• Next, we create a function to make a matrix with zeros and decreases its diagonal elements.
• Then we use the matshow() method, to display an array as a matrix.

Example #2

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
c= a + b

# Plot

plt.plot(a, b, color='red')
plt.plot(a, c, color='m')

# Display

plt.show()``````
• Here we use the mat() function to interpret given input as a matrix.
• We also perform addition operation of two matrix.
• Then we use the plot() method to create a graph.

## Matplotlibb plot numpy array columns

We’ll learn to fetch columns from numpy array and plot using the plot() method of pyplot module of matplotlib.

Example #1

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Create numpy array

data = np.array([1, 2, 3, 4, 5, 6, 7, 8])

# First two columns'

print("First two columns")
print(data[0:2])

# Define data

x= data[0:2]

# Plot

plt.plot(x)

# Display

plt.show()``````
• Here we create a numpy array using array method of numpy.
• Then we fetch first two columns from array.
• To plot a graph, we use the plot() method.

Example #2

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Create numpy array

data = np.array([1, 2, 3, 4, 5, 6, 7, 8])

# Length of an array

length = len(data)

# Last three columns

print("Last 3 Columns")
print(data[length-3:length])

x= data[length-3:length]

# PLot

plt.plot(x)

# Display

plt.show()``````
• Here we create an array using array() method of numpy.
• Then we find the length of array using len() method.
• Then we print and plot last three columns of array using the plot() method.

You may also like to read the following tutorials on Matplotlib.

So, in this Python tutorial, we have discussed the “Matplotlib plot numpy array” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

• Matplotlib plot numpy array
• Matplotlib plot numpy array as line
• Matplotlib scatter plot numpy array
• Matplotlib plot multiple lines from numpy array
• Python plot numpy array as heatmap
• Matplotlib plot numpy array as image
• Matplotlib save plot to numpy array
• Matplotlib plot numpy array 2d
• Matplotlib plot numpy array 3d
• Matplotlib plot numpy matrix
• Matplotlib plot numpy array columns