Introduction to Matplotlib

Related Content

People can understand things better when they see them visually. In Machine Learning, visualization helps us to analyze datasets and get insights out of them. One of Python’s data visualization modules is Matplotlib which is a comprehensive library for creating static, animated, and interactive visualizations. It is a numerical mathematics extension NumPy designed to work with the broader SciPy stack and allows you to create various plots like line, bar, scatter, histogram, etc. In this article, we will cover various types of graphs that you can use to visualize the data using Matplotlib.

Best Machine Learning Books for Beginners and Experts

Best Machine Learning Books for Beginners and Experts

As Machine Learning becomes more and more widespread, both beginners and experts need to stay up to date on the latest advancements. For beginners, check out the best Machine Learning books that can help to get a solid understanding of the basics. For experts, reading these books can help to keep pace with the ever-changing landscape. In either case, a few key reasons for checking out these books can be beneficial. First, they provide a comprehensive overview of the subject matter. Second, they offer insights from leading experts in the field. And third, they offer concrete advice on how to apply machine learning concepts in real-world scenarios. As machine learning continues to evolve, there’s no doubt that these books will continue to be essential resources for anyone looking to stay ahead of the curve.

Installation of Matplotlib

Before using the Matplotlib module, make sure that you have installed the updated version.

The most popular way of installing modules in Python is using pip command:

pip install matplotlib

Once the installation is complete, you can check the version of the matplotlib using the following Python code:

# import the module
import matplotlib as plt

# printing the version
print("The version is : ",plt.__version__)

Output:

introduction-to-matplotlib-version

You can also update the existing version installed Matplotlib on your system by typing the following commands:

pip install --upgrade matplotlib

Simple plot

Let’s start our Matplotlib visualization journey with very basic trigonometry. We will plot the sine(x) and cosine(x) first:

# Importing the required module
import matplotlib.pyplot as plt
import numpy as np
import math

# ndarray object of angles between 0 and 2π using the arange()
x = np.arange(0, math.pi*2, 0.05)

# sin() values on y axis
y = np.sin(x)

# plotting
plt.plot(x,y)

# labeling 
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')

# displaying plot
plt.show()

Output:

introduction-to-matplotlib-sine-wave

In a similar way, we can plot the graph for the cosine wave as shown below:

# ndarray object of angles between 0 and 2π using the arange()
x = np.arange(0, math.pi*2, 0.05)

# cose values on y axis
y = np.cos(x)

# plotting
plt.plot(x,y)

# labeling 
plt.xlabel("angle")
plt.ylabel("cos")
plt.title('cos wave')

# displaying plot
plt.show()

Output:

introduction-to-matplotlib-cosine-wave

Multi plots

So far, we have learned how we can create simple graphs in Matplotlib. Now, we can take a look at how to create multiple subplots on the same canvas. It is easy to compare graphs when they are together rather than when they are in different cells. In this section, we will plot multigraphs using various methods.

subplots function

One of the simplest ways of creating multi-graphs in Matplotlib is to use the subplots() method.

Let’s use this method to plot the sine and cosine wave graphs in the same cell:

# ndarray object of angles between 0 and 2π using the arange()
x = np.arange(0, 2*np.pi, 0.01)

# sin() and cos() values on y axis
y = np.cos(x)
y1 = np.sin(x)

# creating 2 subplots
fig, axs = plt.subplots(2)

# setting the title
fig.suptitle('Subplots')

# cos and sin waves
axs[0].plot(x, y)
axs[1].plot(x, y1)

Output:

introduction-to-matplotlib-subplots

In order to plot the subplot in the horizontal direction, change the arguments in the subplots() method:

# creating 2 subplots
fig, (ax1, ax2) = plt.subplots(1, 2)

# setting the title
fig.suptitle('Subplots')

# cos and sin waves
ax1.plot(x, y)
ax2.plot(x, y1)

Output:

introduction-to-matplotlib-horizontal-graph

Using the above methods, we can plot more than two graphs along with their own title and color of the graph:

# ndarray object of angles between 0 and 2π using the arange()
x = np.arange(0, 2*np.pi, 0.01)

# sin() and cos() values on y axis
y1 = np.cos(x)
y2 = np.sin(x)
y3 = np.arccos(x)
y4 = np.arcsin(x)


# creating subplots for 4 graphs
fig, axs = plt.subplots(2, 2)

# plotting the graphs, title and color
axs[0, 0].plot(x, y1)
axs[0, 0].set_title('cosine wave')
axs[0, 1].plot(x, y2, 'tab:orange')
axs[0, 1].set_title('sine wave')
axs[1, 0].plot(x, y3, 'tab:green')
axs[1, 0].set_title('Arc-cosine wave')
axs[1, 1].plot(x, y4, 'tab:red')
axs[1, 1].set_title('Arc-sine wave')

# we are hiding the x-labels so that the title will be visible
for ax in axs.flat:
    ax.label_outer()

Output:

introduction-to-matplotlib-multiplots

add_subplot function

The add_subplot() function of the Figure class helps us to overwrite the existing graph without removing it. Using this method, we can lay off two plots on top of each other:

# defining the x
x = np.arange(0, math.pi*2, 0.01)

# initializing the figure
fig=plt.figure()

# adding axes
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3])

# ploting the cos and sin wave
axes1.plot(x, np.sin(x))
axes2.plot(x, np.cos(x))
axes1.set_title('sine')
axes2.set_title("cosine")
plt.show()

Output:

introduction-to-matplotlib-add_subplots

We can also specify the color of the graphs and the background as shown below:

# initializing the figure
fig=plt.figure(facecolor='y')

# adding axes
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes2 = fig.add_axes([0.55, 0.55, 0.3, 0.3])

# ploting the cos and sin wave
axes1.plot(x, np.sin(x), 'r')
axes2.plot(x, np.cos(x), 'g')
axes1.set_title('sine')
axes2.set_title("cosine")
plt.show()

Output:

introduction-to-matplotlib-add_plots

subplot2grid function

The subplot2grid() function gives more flexibility in creating an axes object at a specific location of the grid. It also helps in spanning the axes object across multiple rows or columns. In simple words, this function is used to create multiple charts within the same figure.

For example, let’s plot sine, cosine, and tan waves using this function:

# using subplot2grid function 
sin_wave = plt.subplot2grid((3,3),(0,0),colspan = 2)
cos_wave = plt.subplot2grid((3,3),(0,2), rowspan = 3)
tan_wave = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2)

# creating the x
x = np.arange(0, math.pi*2, 0.01)

# plotting the graphs
sin_wave.plot(x, np.tan(x))
sin_wave.set_title('tan wave')
cos_wave.plot(x, np.cos(x))
cos_wave.set_title('cose wave')
tan_wave.plot(x, np.sin(x))
tan_wave.set_title('sin wave')

# showing
plt.tight_layout()
plt.show()

Output:

introduction-to-matplotlib-subplot2grid

Formatting plots

In this section, we will use different methods to format our plots. We will learn how to set up the grid, format axes, set limits, and labeles.

Grids

The grid() function of the Axes class sets the visibility of the grid for the figure. Moreover, you can set color, line style, and line width properties as well.

Let’s visualize the cosine wave graph with grids:

fig, axes = plt.subplots(1,2, figsize = (12,4))

# creating the x
x = np.arange(0, math.pi*2, 0.01)

# graph with grid
axes[0].plot(x, np.cos(x))
axes[0].grid(True)
axes[0].set_title('default grid')

axes[1].plot(x,np.cos(x))
axes[1].set_title('no grid')

# plotting
fig.tight_layout()
plt.show()

Output:

introduction-to-matplotlib-grids

We can also customize the grids as shown below:

# creating three subplots
fig, axes = plt.subplots(1,3, figsize = (12,4))

# creating the x
x = np.arange(0, math.pi*2, 0.01)

# default grid
axes[0].plot(x, np.cos(x))
axes[0].grid(True)
axes[0].set_title('default grid')

# custom grid
axes[1].plot(x, np.cos(x))
axes[1].grid(color='r', ls = '-.', lw = 0.5)
axes[1].set_title('custom grid')

# no grid
axes[2].plot(x,np.cos(x))
axes[2].set_title('no grid')
fig.tight_layout()
plt.show()

Output:

introduction-to-matplotlib-grids-custom

Formatting axes

We can format the axes by labeling them or by changing the scaling. The scaling of the axes has a great impact on the shape of the graph so it is important to scale the graph accordingly. For example, see below two graphs that represent the same function but on different scaling.

# initializaing the subplots
fig, axes = plt.subplots(1, 2, figsize=(10,4))
x = np.arange(0, math.pi*2, 0.01)

# normal scaling 
axes[0].plot(x,np.cos(x), label='Cosine')
axes[0].set_title("Normal scale")

# scalling based on log
axes[1].plot(x, np.cos(x))
axes[1].set_yscale("log")
axes[1].set_title("Logarithmic scale y_axis")


# labeling
axes[0].set_xlabel("x axis")
axes[0].set_ylabel("y axis")
axes[1].set_xlabel("x axis")
axes[1].set_ylabel("y axis")
plt.show()

Output:

introduction-to-matplolib-scalling

Both the graph represents the same information but because different y_axis scaling value applies, they look totally different.

Setting limits

So far we have seen that Matplotlib automatically puts the minimum and maximum values of variables to be displayed along the “x” and “y” axes of a plot. We can also specify those limits by using the set_xlim() and set_ylim(). For example, see the plotting below:

# creating two subplots
fig, axes = plt.subplots(1,2, figsize = (12,4))

# creating the x
x = np.arange(0, 5, 0.5)

# default scalling
axes[0].plot(x, np.exp(x))
axes[0].set_title('default scalling')

# setting limits
axes[1].plot(x, np.exp(x))
axes[1].set_title('setting limits')
axes[1].set_ylim(0,1000)
axes[1].set_xlim(0,10)

plt.show()

Output:

introduction-to-matplotlib-setting-limits

Although both graphs represent the same information, the scaling on both axes is different.

Setting labels

So far we have seen that Matplotlib automatically takes over the task of spacing points on the axis. However, we can locate and format the data points on both axes by passing a list object as an argument to the xticks() and yticks() functions.

Let’s plot the sine wave by labeling the x-axis data points and y-axis data points:

# creating x axis
x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()

# main axis
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
y = np.sin(x)
ax.plot(x, y)

# labeling
ax.set_xlabel('angle')
ax.set_title('sine wave')
ax.set_xticks([0,2,4,6,])
ax.set_xticklabels(['0','60','120', '180'])
ax.set_yticks([-1,0,1])
ax.set_yticklabels(['Negative 0ne', 'Zero', 'Positive one'])
plt.show()

Output:

introduction-to-matplotlib-setting-labels

Bar plots

A bar plot is a plot that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. One axis of the chart shows the specific categories being compared, and the other axis represents a measured value.

The bar() method of the Matplotlib takes two required arguments:

  • x: The x coordinates of the bar plot.
  • y or height: The height or the value of each value.

It also takes a number of other optional arguments as well.

Simple bar plot

Let’s create a simple categorical dataset and visualize it by using a bar chart:

# creating dataset
data_dict = {'Physics':96, 'Math':56, 'English':70}

# course vs marks
courses = list(data_dict.keys())
marks = list(data_dict.values())

# plotting
fig = plt.figure(figsize = (10, 5))

#  Bar plot
plt.bar(courses, marks, color ='green',
        width = 0.8)

# labeling
plt.xlabel("Courses")
plt.ylabel("Marks obtained")
plt.title("Student marks obtained out of 100")
plt.show()

Output:

introduction-to-matplotlib-simple-bar-plot

Unstacked bar plots

We usually use unstacked bar graphs when we want to compare a certain category, especially over time with different samples. It can be used to deduct some facts from the pattern we observe through the comparison. For example, when comparing several quantities and when one variable is changing, we might want a bar chart where we have bars of one color for each quantity value.

Let’s create a dataset for four students having different marks in three different subjects and we compare their marks using unstack bar chart.

# importing the required module
import pandas as pd

# creating dataset
data = pd.DataFrame({
    "Physics":[50,60,67,89],
    "Math":[69,31,90,79],
    "English":[73,78,80,54]},
    index=["Bashir", "Mirzo", "Erlan", "Eliman"])

# ploting the bar chart
data.plot(kind="bar",figsize=(15, 8))

# labeling
plt.title("Students marks out of 100")
plt.xlabel("Subjects")
plt.ylabel("Obtain marks")
plt.show()

Output:

introduction-to-matplotlib-unstacked-plots

Another method to create a similar unstacked bar plot is using the bar() method. We can plot multiple bar charts by playing with the thickness and the positions of the bars. Our data contains three subjects, and obtain the marks of four students. We will create bars having a thickness of 0.25 units. Each bar chart will be shifted 0.25 units from the previous one as shown below:

# initializing the plot
fig = plt.figure()
X = np.arange(4)
ax = fig.add_axes([0,0,1,1])

# Plotting the graph for each of the subject
ax.bar(X + 0.00, data['Physics'], color = 'b', width = 0.25)
ax.bar(X + 0.25, data["Math"], color = 'r', width = 0.25)
ax.bar(X + 0.50, data["English"], color = 'g', width = 0.25)

# adding legends
ax.legend(labels=data[0:0])

# setting the x-asix
ax.set_xticks([0,1.5,2.5,3.5,])
ax.set_xticklabels(['Bashir','Mirzo','Erlan', 'Eliman'])

Output:

introduction-to-matplotlib-unstacked-bar-plt

Stacked bar plots

The stacked bar plots are the plots that represent different groups on top of each other. The height of the resulting bar shows the combined result of the groups. We will now plot the bar chart of each subject appended to one another for each student.

# initialiazing the plot
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])

# ploting stacked bar plots
ax.bar(X, data['Physics'], width = 0.4, color='r')
ax.bar(X, data['Math'], width=0.4,bottom=data['Physics'], color='b')
ax.bar(X, data['English'], width=0.4,bottom=data['Math']+data['Physics'], color='g')

# labeling
ax.set_ylabel('Total marks')
ax.set_title('Students marks')
ax.legend(labels=['Physics', 'Math', 'English'])

# setting the x-asix
ax.set_xticks([0,1,2,3,])
ax.set_xticklabels(['Bashir','Mirzo','Erlan', 'Eliman'])
plt.show()

Output:

introduction-to-matplotlib-stacked-plots

Pie plots

A Pie plot is a type of graph in which a circle is divided into sectors that each represent a proportion of the whole. Matplotlib has a pie() function that generates a pie diagram representing data in an array. It can take the following arguments:

  • x: The array.
  • labels: a sequence of strings providing the labels.
  • colors: A sequence of matplotlib color arguments through which the pie chart will cycle.
  • Autopct: It is a string used to label the wedges with their numeric value.
  • shadow: It is used to create the shadow.

Simple pie plot

Let’s now create a very simple dataset and plot that dataset using a pie chart:

# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
        'TESLA', 'JAGUAR', 'MERCEDES']
 
data = [23, 17, 35, 29, 12, 41]
 
# Creating plot
fig = plt.figure(figsize =(10, 7))
plt.pie(data, labels = cars)
 
# show plot
plt.show()

Output:

introduction-to-matplotlib-pie-plot

Customizing pie chart

A pie chart can be customized on the basis of several aspects. The startangle attribute rotates the plot by the specified degrees in a counterclockwise direction performed on the x-axis of the pie chart. The shadow attribute accepts a boolean value, if it is true then the shadow will appear below the rim of the pie.

Let’s apply different customization and plot pie charts:

# Creating explode data
explode = (0.1, 0.0, 0.2, 0.3, 0.0)
 
# Creating color parameters
colors = ( "red", "cyan", "indigo","green", "gray")
 
# Wedge properties
wp = { 'linewidth' : 3, 'edgecolor' : "black" }
 
# Creating autocpt arguments
def func(pct, allvalues):
    abslt = int(pct / 100.*np.sum(allvalues))
    return "{:.1f}%\n({:d} marks)".format(pct, abslt)
 
# Creating plot
fig, ax = plt.subplots(figsize =(15, 10))
wedges, texts, autotexts = ax.pie(marks,
                                  autopct = lambda pct: func(pct, marks),
                                  explode = explode,
                                  labels = names,
                                  shadow = True,
                                  colors = colors,
                                  startangle = 90,
                                  wedgeprops = wp,
                                  textprops = dict(color ="black"))
 
# Adding legend
ax.legend(wedges, names,
          title ="Marks obtained",
          loc ="center left",
          bbox_to_anchor =(1, 0, 0.5, 1))
plt.setp(autotexts, size = 10, weight ="bold")
ax.set_title("Marks obtained by students")
 
# show plot
plt.show()

Output:

introduction-to-matplotlib-pie-customization

Scattered plots

Scatter plots are a good way of displaying two sets of data. to see if there is a correlation or connection. It is a graph with the independent variable on the horizontal axis and the dependent variable on the vertical axis. For each pair of data, there is a dot or a symbol where the x-axis value intersects the y-axis value.

The scatter() method is used to plot scattered plots which take data on the x-axis, data on the y-axis, and a number of other optional arguments.

Simple scattered plot

A simple scattered plot takes two arguments. Frist data is for the x-axis and the second data for the y-axis.

For example, let’s create a simple dataset and then will visualize it by using a scattered plot:

# creating random dataset
x_axis = np.array(np.random.randint(4, size=(30)))
y_axis = np.array(np.random.randint(100, size=(30)))

# plotting simple scattered plot
plt.scatter(x_axis, y_axis)
plt.show()

Output:

introduction-to-matplotlib-scattered

Merging scattered plots

Merged scattered plots can be very useful to compare several datasets.

For example, let’s plot the sine wave and cosine wave using a scatter plot:

# creating independent variable
x = np.arange(0, math.pi*2, 0.1)


# ploting sine wave
plt.scatter(x, np.sin(x), color='r')

# plotting cosine wave
plt.scatter(x, np.cos(x), color='g')

plt.show()

Output:

introduction-to-matplotlib-comparing-scattered-plots

Size and transparency of dots

We can also specify the sizes and transparency to make it more informative. For example, we will plot the sine wave and cosine wave by specifying the sizes of each of the points to be random ( form 10000) and will plot then using a scatter plot with the transparency of 0.5.

# creating independent variable
x = np.arange(0, math.pi*2, 0.8)

# creating sizes of random sizes
S=[]
for i in range(len(x)):
    S.append(np.random.randint(10000))
    
# ploting sine wave
plt.scatter(x, np.sin(x), color='r', s=S, alpha=0.5)
# plotting cosine wave
plt.scatter(x, np.cos(x), color='g' , s=S, alpha=0.5)

plt.show()

Output:

introduction-to-matplotlib-scattered-plot-with-transparancy

Color with size and transparency

We can also combine a colormap with different sizes on the dots. This is best visualized if the dots are transparent.

Let’s create a random dataset and will visualize it with different colors and dot sizes. We can also specify the colormap with the keyword argument cmap with the value of the colormap, in this case, 'viridis' which is one of the built-in colormaps available in Matplotlib. In addition, we will create an array with values (from 0 to 100), one value for each of the points in the scatter plot:

# creating  random dataset
x_axis = np.random.randint(100, size=(100))
y_axis = np.random.randint(100, size=(100))
colors = np.random.randint(100, size=(100))
sizes = 10 * np.random.randint(100, size=(100))

# ploting the graph
plt.scatter(x_axis, y_axis, c=colors, s=sizes, alpha=0.5, cmap='nipy_spectral')

# plotting the color bar as well
plt.colorbar()
plt.show()

Output:

introduction-to-matplotlib-scatter-plot

Box plot

A box plot is a simple way of representing statistical data on a plot in which a rectangle is drawn to represent the second and third quartiles, usually with a vertical line inside to indicate the median value. The lower and upper quartiles are shown as horizontal lines on either side of the rectangle.

introduction-to-matplotlib-box-plot-diagram

The boxplot() method in the Matplotlib module is used to plot the boxplots which can take the following parameters.

  • data: array to be plotted.
  • vert: It is an optional parameter that accepts the boolean values for vertical and horizontal plotting.
  • bootstrap: It is also an optional parameter that specifies intervals around notched boxplots.
  • positions: It is an optional parameter that accepts an array and sets the position of boxes.
  • widths: It is an optional parameter that accepts an array and sets the width of boxes.
  • labels: It is a sequence of strings that sets labels for each dataset.
  • order: It sets the order of the boxplot.

Simple box plot

Let’s plot a very simple box plot using the Matplotlib module.

First, we need a random dataset which we will visualize afterward:

# Creating dataset
data = np.random.normal(1000, 20, 200)
 
# ploting size
fig = plt.figure(figsize =(10, 7))
 
# Creating plot
plt.boxplot(data)
plt.show()

Output

introduction-to-matplotlib-simple-boxplot

The dot points outside the box plot shows the outliers in our dataset.

Multi-box plotting

We can also plot multi-box plots by specifying the axes. For example, let’s create four random datasets and then plot box plots for each of them:

# creating random dataset
data1 = np.random.normal(1000, 100, 200)
data2 = np.random.normal(500, 90, 200)
data3 = np.random.normal(880, 300, 200)
data4 = np.random.normal(700, 90, 200)
data = [data1, data2, data3, data4]

# plot size
fig = plt.figure(figsize =(10, 7))
 
# Creating axes instance
ax = fig.add_axes([0, 0, 1, 1])
 
# Creating plot
bp = ax.boxplot(data)
plt.show()

Output:

introduction-to-matplotlib-multi-box-plots

Violin plots

A violin plot is a hybrid of a box plot and a kernel density plot, which shows peaks in the data. It is used to visualize the distribution of numerical data. Unlike a box plot that can only show summary statistics, violin plots depict summary statistics and the density of each variable.

The violinplot() in matplotlib can take the following parameter:

  • data: This parameter denotes the array or sequence of vectors.
  • positions: This parameter is used to set the positions of the violins.
  • vert: This parameter contains the boolean value. If the value of this parameter is set to true then it will create a vertical plot, otherwise, it will create a horizontal plot.
  • showmeans: This parameter contains the boolean values. If the value of this parameter is True, then it will toggle the rendering of the means.
  • showextrema: This parameter contains the boolean values. If the value of this parameter is True, then it will toggle the rendering of the extrema.
  • showmedian: This parameter contains the boolean values. If the value of this parameter is True, then it will toggle the rendering of the medians.

Simple violin plot

We will now visualize the violin plot on a random dataset using the Matplotlib module.

Let’s first create a random dataset and then will visualize using a violin plot:

# creating a random dataset
data = np.random.randint(1000, size=(100))

# plotting simple violin plot
plt.violinplot(data, showmeans=True, showextrema=True, showmedians=True)
plt.show()

Output:

introduction-to-matplotlib-violin-plots-simple

Multi-violin plots

Now let’s create some normal distributions and visualize them using violin plots:

# creating a random dataset
data1 = np.random.normal(1000, size=(100))
data2 = np.random.normal(1000, size=(100))
data3 = np.random.normal(1000, size=(100))
data4 = np.random.normal(1000, size=(100))

data = [data1, data2, data3, data4]
# plotting simple violin plot
plt.violinplot(data, showmeans=True, showextrema=True, showmedians=True)
plt.show()

Output:

introduction-to-matplotlib-multi-violin-plots

Stem plot

A Stem plot plots vertical lines at each x position covered under the graph from the baseline to y and places a marker there. In this section, we will plot the stem plot of sine and cosine waves.

# creating the data
x = np.arange(0, math.pi*2, 0.1)

# plotting for cosine wave
plt.stem(x, np.cos(x))
plt.show()

Output:

introduction-to-matplotlib-stem-plot

Moreover, we can also customize the plot to make it more beautiful and informative.

# customizing the stem plot
plt.stem(x, np.sin(x), linefmt='green', markerfmt='*', bottom=0, label="Sine")
plt.stem(x, np.cos(x), linefmt='red', markerfmt='-', bottom=0, label="Cosine")
plt.show()

Output:

introduction-to-matplotlib-stem-plt

Quiver plots

A quiver plot is basically a type of 2D plot which shows vector lines as arrows. This type of plot is useful for Electrical engineers to visualize electrical potential and show stress gradients in Mechanical engineering.

The quiver() method in the Maplotlib is used to plot the quiver plot which can take the following parameters:

  • x_cordinate: x-coordinate of the arrow location.
  • y_cordinate: y-coordinate of the arrow location.
  • x_direction: x-component of the direction of the arrow.
  • y_direction: y-component of the direction of the arrow.
  • scale: Used to scale the plotting.
  • angle: used to determine the angle of the arrow vectors plotted.

Quiver plot with one and two arrows

Let’s plot the quiver plot with one and two arrows. First, let’s plot one arrow quiver plot with the x and y coordinate at zero and with the x, and y-direction:

# Creating arrow
x_position = 0
y_position = 0
x_direction = 1
y_direction = 1
 
# Creating plot
fig, ax = plt.subplots(figsize = (10, 6))
ax.quiver(x_position, y_position, x_direction, y_direction)
ax.set_title('Quiver plot')
plt.show()

Output:

introduction-to-matplotlib-quiver-plot

Now, let’s plot a similar plot with two arrows centered at 0, 0:

#setting position and direction
x_position = [0, 0]
y_position = [0, 0]
x_direction = [1, 2]
y_direction = [1, -1]
 
# Creating plot
fig, ax = plt.subplots(figsize = (10, 6))
ax.quiver(x_position, y_position, x_direction, y_direction, scale=5)
plt.show()

Output:

introduction-to-matplotlib-quiver-plot

Quiver plot using meshgrid method

A quiver plot containing two arrows is a good start, but it is too much time to add arrows to the quiver plot one by one. So to create a fully 2D surface of arrows we will use the meshgrid() method of Numpy. A meshgrid() function is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matrix indexing.

Let’s use the meshgrid() function and plot a quiver plot:

# Creating arrows
x = np.arange(0, 2, 0.1)
y = np.arange(0, 2, 0.1)
 
# meshgrid method
X_coordinate, Y_coordinate = np.meshgrid(x, y)

# setting direction
x_direction = np.cos(X)
y_direction = np.sin(Y)
 
# creating plot
fig, ax = plt.subplots(figsize =(14, 8))
ax.quiver(X_coordinate, Y_coordinate, x_direction, y_direction)
plt.show()

Output:

introduction-to-matplotlib-quiver-plotting

Three-dimensional plotting

3D scatter plots are used to plot data points on three axes in an attempt to show the relationship between three variables. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X, Y, and Z axes. In this section, we will plot various kinds of plots that we have covered in 3-dimensional space.

Apart from the Matplotlib module, we can also import the mplot3d module from mpl_toolkits which is required for enabling 3D projections.

Let’s create a 3D space for plotting:

# importing the required module
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# size of the figure
fig = plt.figure(figsize=(8,8))


# 3-d plot
ax = fig.add_subplot(projection='3d')

Output:

introduction-to-matplotlib-3-d-space

3D line plot

Now, we can plot a line graph in 3D space. Let’s create sine and cos waves to visualize it in 3D space:

# initializing the 3-d space
# initializing the 3-d space
fig = plt.figure(figsize=(8,8))
ax = plt.axes(projection='3d')

# creating the variables
z = np.arange(0, math.pi*2, 0.1)
x =  np.sin(z)
y= np.cos(z)

# plotting
ax.plot3D(x, z, z, 'green')
ax.plot3D(y, z, z, 'red')

ax.set_title('3-D line plot')
plt.show()

Output:

introductiont-to-maplotlib-3-d-line-plot

3D scattered plot

Plotting a three-dimensional scattered plot is very similar to the line plot. Let us now visualize the same functions using a scattered plot in three-dimensional space.

# initializing the 3-d space
fig = plt.figure(figsize=(8,8))
ax = plt.axes(projection='3d')

# plotting
ax.scatter(z, z, x, 'green')
ax.scatter(z, z, y, 'red')

ax.set_title('3-D scatter plot')
plt.show()

Output:

introduction-to-matplotlib-scatter-plot

3D contour plot

One of the best ways to visualize any mathematical function is using contour plots. For example, let’s visualize the sinusoidal on the three-dimensional graph using a counterplot:

# function to return sinusoidal function
def f(x, y):
   return np.sin(np.sqrt(x ** 2 + y ** 2))

# creating x and y
x = np.linspace(-10, 10, 50)
y = np.linspace(-10, 10, 50)

# using meshgrid function for x and y
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

# plotting the graph
fig = plt.figure(figsize=(8, 8))
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50)
ax.set_title('3-D contour plot')
plt.show()

Output:

introduction-to-matplotlib-contour-plot

3D wireframe plot

Wireframe plot is another way to plot in three-dimensional space that takes a grid of values and projects it onto the specified three-dimensional surface and can make the resulting three-dimensional forms quite easy to visualize.

We will again use the same function and visualize it using this wireframe plot:

fig = plt.figure(figsize=(8,8))
ax = plt.axes(projection='3d')

#wirefram plot
ax.plot_wireframe(X, Y, Z, color='green')
ax.set_title('Wireframe plot')
plt.show()

Output:

introdution-to-matplotlib-wireframe-plot

3D surface plot

Surface plots are diagrams of three-dimensional data. Rather than showing the individual data points, surface plots show a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z).

Let’s visualize the sinusoidal function using the surface plot:

# size of the 3-d plot
fig = plt.figure( figsize=(8, 8))
ax = plt.axes(projection='3d')

# surface plot
ax.plot_surface(X, Y, Z, color='green')
ax.set_title('Surface plot')
plt.show()

Output:

introduction-to-matplotlib-surface-plot

Image functions in Matplotlib

Apart from plotting various kinds of graphs, the Maplotlib library can also be used to read, save and view images. The two of the most important methods are the imread() and imshow() functions. In this section, we will be using a sample image to illustrate read, save and show operations:

Read image

The imread() method in matplotlib.image module is used to read images. Let’s read an image using the imread() method:

# importing the required module
import matplotlib.image as img
  
# reading the image using imread()
sample_image = img.imread('Image.png')
  
# displaying the image as an array
print(sample_image)

Output:

introduction-to-matplotlib-imread-function

Displaying image

The imshow() method in Maplotlib is used to display an image. Let’s use this method to display the image that we’ve read:

# reading the image using imread()
sample_image = img.imread('Image.png')
  
# displaying the image 
plt.imshow(sample_image)

Output:

introduction-to-maplotlib-imshow-image

Modifying image

As we know that an image consists of an array of numeric numbers so any change to these numbers will modify the image.

Let’s play with these numbers and modify our original image:

# modifying the shape of the image
modifiedImage =  sample_image[40:200, 50:200, 1]
  
# shape difference
print(modifiedImage.shape)
print(sample_image.shape)

Output:

introduction-to-matplotlib-modified

The shape of the modified image is not the same as the original image.

Let’s display the modified image:

# display the image
plt.imshow(modifiedImage)

Output:

introduction-to-maplotlib-image

Summary

Matplotlib is a plotting library for the Python programming language. It is used to plot data by using various kinds of graphs. In this article, we covered how to use the Matplotlib module and visualize different datasets through various kinds of plots. Additionally, we’ve covered how to read and display images using the Matplotlib module.

LIKE THIS ARTICLE?
Facebook
Twitter
LinkedIn
Pinterest
WANT TO BE AN AUTHOR OF ANOTHER POST?

We’re looking for skilled technical authors for our blog!

Table of Contents