To plot an NumPy array with Matplotlib, follow these steps:
- Create your NumPy array/s.
- Import the Matplotlib or Seaborn data visualization libraries.
- Create your plot figure and axes objects
- Use matplotlib or Seaborn to assign the array data to the chart axes, determine the chart color map, define the markers etc’.
- Set a title for your chart and for the axes.
- Optionally add your a legend to your chart.
Example: Create a bar plot from a Numpy array
#1 – Create sample data
We’ll start by creating two numpy arrays:
import numpy as np
# create arrays
x = np.arange(0,10,1)
y = x**2
#2 – Import visualization libraries
Next step is to import matplotlib or Seaborn so you can use them in your script
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
#3 – Draw the chart
To render the bar chart from the arrays with matplotlib proceed as following:
fig, ax = plt.subplots()
ax.bar (x,y)
ax.set_title ('My Plot (w MatplotLib)');
Here’s the chart:
If you prefer to use Seaborn, you might need a slightly different code:
# create a dictionary and pandas DataFrame
my_dict = dict(x=x,y=y)
data = pd.DataFrame (my_dict)
fig, ax1 = plt.subplots()
# render the graph
ax1 = sns.barplot(x='x', y='y', data=data, )
ax1.set_title("My Plot (w Seaborn)");
Here’s the bar chart:
Create a scatter plot from an array
Next case is to render a scatter plot showing an array of points. We’ll use the same data:
fig, ax = plt.subplots()
ax.scatter (x,y)
ax.set_title ('Scatter (w MatplotLib)');
Here’s our scatter chart:
Related: You might want to take a look at our tutorial on creating line charts in matplotlib.
Plotting a 2d array
In the next case we will first create a 2d array and then use the matplotlib imshow() function to render it as a picture
#create 2 d array
my_array = np.array ([[10,20,30], [100,220,330], [500,600,700]])
# make a graph us
fig, ax = plt.subplots()
ax.imshow(my_array, cmap='plasma');
Here’s the result:
A different option is to use Seaborn heatmap to render a somewhat similar chart from our two dimensional Numpy Array. First we’ll construct a pandas DataFrame and then using Seaborn to draw the graph:
# construct DataFrame from Numpy Array
my_data = pd.DataFrame(data = my_array)
# create the plot
fig, heat_plot = plt.subplots()
heat_plot = sns.heatmap(data=my_data,cmap='plasma' )
heat_plot.set_title("Heatmap plot (w Seaborn)");
Here’s the resulting chart: