Learn Matplotlib with Python for Data Science in this full course curated by the data science team at Kharpann.

Matplotlib is the most used data visualization library in Python for data analysis and infographics. In this course, you will learn how to use the Matplotlib library to create amazing plots. You will learn the basics of Matplotlib, how to plot 2D and 3D data plots, how to save plots in Matplotlib and how to work with images in Matplotlib.

### Chapter I: Introduction to Matplotlib Plots

Matplotlib is a data visualization library in Python used for plotting static, animated and interactive visualizations with a high level of flexibility. In Python, there are multiple kinds of Matplotlib plots available and in this course, we will go over everything required to start creating such Matplotlib plots.

**Prerequisites for this course on Matplotlib**

Before diving deep into this course and learning how to create your first Matplotlib plot, you are required to have some basic knowledge of Python.

If you do not have any prior knowledge about Python , make sure to complete the following courses first:

Please feel free to continue onwards with the chapter once you are done with the course.

**Installing Matplotlib in Python using pip**

Matplotlib can be installed using the Python Package Manager, pip, as follows:

$ pip install matplotlib

**Note: **If you are using Anaconda, Matplotlib comes pre-installed.

**Importing Matplotlib in Python**

Starting from this section onwards, we will be using Jupyter Notebooks as our Python IDE.

To import Matplotlib in Python, write the following code and run it:

# Libraries/Modules import conventions import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline

**Check Matplotlib version in Python**

To check the version of the installed Matplotlib library, write the following code and run it:

# Check version of matplotlib installed print(mpl.__version__) #Printed version: 3.1.1

The output of the code will be displayed as following in Jupyter Notebook:

If your Matplotlib version is greater than 3.0.0, then everything is now ready!

Now you can finally start plotting your own Matplotlib plots in Python. Head over to the next chapter and learn the basics of a Matplotlib plot.

### Chapter II: Basics of a Matplotlib Plot

In this chapter, we will get to learn about all the basic terminologies/properties of a Matplotlib plot through visual examples and descriptive code.

By learning about the terminologies, we can start to create our own line plot using Matplotlib. We will also change the different properties of a line plot and explore everything that there is to plotting with Matplotlib.

**The terminologies of a Matplotlib plot**

The following diagram shows the different terminologies used to describe a Matplotlib plot. Learning these at the beginning will be helpful since most methods used for plotting Matplotlib plots are based on the terminologies.

**Title:**The title of a Matplotlib plot is the heading that appears at the top of the figure.**Axes:**It is the region where data is plotted on a Matplotlib plot.**Axis:**These are the number-line-like objects. They take care of setting the graph limits and generating the ticks (the marks on the axis) and tick labels (strings labelling the ticks).**Grid:**It is the dotted line that divides the axes into multiple equal square spaces.**Label:**It is the notation for axis. For instance, we can define the x-axis label and y-axis label names.**Legend:**It is the notation for plots in the figure. It is often represented with distinct colours, shapes, and names.**Figure:**A figure in Matplotlib means the whole window in the user interface. Within this figure, there can be “subplots” that help to arrange plots in a regular grid where we need to specify the number of rows and columns and the number of the plot.

**Plotting your first Matplotlib Line Plot**

In this section, you will learn how to plot a simple line plot in Matplotlib.

First, import the Matplotlib library in Python using the knowledge gained from the previous chapter.

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline

Since we need some data to plot, let us define two Python lists representing the points of the line that we are about to plot.

# Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8]

Now, we can plot a line plot using the plot() method and show that plot using the show() method:

# plot() is used for plotting a line plot and show() is used for displaying the plot plt.plot(X, Y) plt.show()

Piecing all the code together, this is how you create a line plot in Matplotlib.

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] # plot() is used for plotting a line plot and show() is used for displaying the plot plt.plot(X, Y) plt.show()

Congratulations, you just made your first plot in Matplotlib! Moving onwards, we will try to make this plot even more informative and interesting by using the various properties mentioned at the beginning of this chapter.

**Adding a Title and Axis Labels onto the Matplotlib plot**

You can provide a title and axis labels to the plot using the title(), xlabel() and ylabel() methods as shown below:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] # plot() is used for plotting a line plot plt.plot(X, Y) # Adding title, xlabel and ylabel plt.title('A Basic Line Plot') #Title of the plot plt.xlabel('X-axis') #X-Label plt.ylabel('Y-axis') #Y-Label # show() is used for displaying the plot plt.show()

**Changing the color and width of the line plot**

We can change the color and width of the line plot by defining the ‘color’ and ‘linewidth’ properties as follows:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] # plot() is used for plotting a line plot plt.plot(X, Y, color = 'green', linewidth = 5) # Adding title, xlabel and ylabel plt.title('A Basic Line Plot') #Title of the plot plt.xlabel('X-axis') #X-Label plt.ylabel('Y-axis') #Y-Label # show() is used for displaying the plot plt.show()

**Changing the figure size of the line plot**

The dimensions (width and height) of the line plot can be changed as following by defining a figure() method before plotting as follows:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] # Defining the figure shape fig = plt.figure(figsize = (10, 4)) # Width is 10 and height is 4 # plot() is used for plotting a line plot plt.plot(X, Y, color = 'green', linewidth = 5) # Adding title, xlabel and ylabel plt.title('A Basic Line Plot') #Title of the plot plt.xlabel('X-axis') #X-Label plt.ylabel('Y-axis') #Y-Label # show() is used for displaying the plot plt.show()

**Annotating Text and adding an arrow onto the Matplotlib Line Plot**

We can annotate text at a particular position of the plot using the annotate() method by specifying the following properties:

- xy: The point *(x,y)* to annotate.
- xytext: The position *(x,y)* to place the text at.
- arrowprops: Properties of the arrow as a dictionary.

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] # Defining the figure shape fig = plt.figure(figsize = (10, 4)) # Width is 10 and height is 4 # plot() is used for plotting a line plot plt.plot(X, Y, color = 'green', linewidth = 5) # Adding annotations plt.annotate('This is a line', xy=(2.5, 5.5), xytext=(1.5, 7), arrowprops={'facecolor':'black', 'shrink':0.05}, ) # Adding title, xlabel and ylabel plt.title('A Basic Line Plot') #Title of the plot plt.xlabel('X-axis') #X-Label plt.ylabel('Y-axis') #Y-Label # show() is used for displaying the plot plt.show()

**Adding another line plot onto the same figure**

To add another line plot into the same figure, we can call the plot() method again for another set of data. Here, new data is added in the form of lists (A and B) and plotted using the plot() method.

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] A = [1, 2, 3, 4] B = [1, 2, 3, 4] # Defining the figure shape fig = plt.figure(figsize = (10, 4)) # Width is 10 and height is 4 # plot() is used for plotting a line plot plt.plot(X, Y, color = 'green', linewidth = 5) plt.plot(A, B, color = 'red', linewidth = 5) # Adding annotations plt.annotate('This is a line', xy=(2.5, 5.5), xytext=(1.5, 7), arrowprops={'facecolor':'black', 'shrink':0.05}, ) # Adding title, xlabel and ylabel plt.title('A Basic Line Plot') #Title of the plot plt.xlabel('X-axis') #X-Label plt.ylabel('Y-axis') #Y-Label # show() is used for displaying the plot plt.show()

**Displaying a Legend on the Matplotlib Line Plot**

Legends are used when more than one plot is made in the same figure. A legend can be displayed using Matplotlib’s legend() method.

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] A = [1, 2, 3, 4] B = [1, 2, 3, 4] # Defining the figure shape fig = plt.figure(figsize = (10, 4)) # Width is 10 and height is 4 # plot() is used for plotting a line plot plt.plot(X, Y, color = 'green', linewidth = 5) plt.plot(A, B, color = 'red', linewidth = 5) # Adding annotations plt.annotate('This is a line', xy=(2.5, 5.5), xytext=(1.5, 7), arrowprops={'facecolor':'black', 'shrink':0.05}, ) # Adding title, xlabel and ylabel plt.title('A Basic Line Plot') #Title of the plot plt.xlabel('X-axis') #X-Label plt.ylabel('Y-axis') #Y-Label # Giving labels to each line (to be shown in the legend) plt.legend(['Green Line', 'Red Line']) # show() is used for displaying the plot plt.show()

**Plotting subplots in Matplotlib**

Sometimes it is necessary to plot multiple plots within a single figure. In such cases, we use the subplots() function of Matplotlib which returns a tuple (`fig`

, `ax`

), giving a single figure `fig`

with an array of axes `ax`

.

Let us plot the two lines shown in the previous example in two different plots using subplots():

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] A = [1, 2, 3, 4] B = [1, 2, 3, 4] # Defining the figure shape fig, ax = plt.subplots(1, 2) # One row and two columns # plot() is used for plotting a line plot ax[0].plot(X, Y, color = 'green', linewidth = 5) ax[1].plot(A, B, color = 'red', linewidth = 5) # show() is used for displaying the plot plt.show()

Now you know the basics of a Matplotlib plot and you can start plotting your own line plots as needed.

Starting from the next chapter, we will learn how to plot other kinds of plots using Matplotlib and not just line plots. Head over to the next chapter to learn about the different available 2D plots in Matplotlib.

### Chapter III: Plotting 2D plots in Matplotlib

Now that you have learned the basics of a Matplotlib plot, we will be exploring the different kinds of 2D plots that can be made in Matplotlib.

A 2D plot is a plot where data is plotted on only the x and y-axis. 2D plots are mostly used in reporting and infographics and it is important to know how to plot such Matplotlib plots if you are a numerical analyst. The different types of 2D plots covered in this chapter are:

- Matplotlib Line Plot
- Matplotlib Scatter Plot
- Matplotlib Bar Plot
- Matplotlib Pie Chart
- Matplotlib Histogram

**Matplotlib Line Plot – How to make a line plot in Matplotlib?**

A Matplotlib Line Plot can be made using the plot() function of Matplotlib pyplot.

For plotting a Matplotlib Line Plot, we will have to specify the data for the x-axis and y-axis as shown in the example below:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] # plot() is used for plotting a line plot plt.plot(X, Y) # Adding title, xlabel and ylabel plt.title('A Basic Line Plot') # Title of the plot plt.xlabel('X-axis') # X-Label plt.ylabel('Y-axis') # Y-Label # show() is used for displaying the plot plt.show()

To learn more about the different variations of a line plot, please make sure to read the chapter on ‘Basics of a Matplotlib Plot‘.

**Matplotlib Scatter Plot – How to make a scatter plot in Matplotlib?**

A Matplotlib Scatter Plot can be made using the scatter() function of Matplotlib pyplot.

For plotting a Matplotlib Scatter Plot, we will have to specify the data for the x-axis and y-axis as shown in the example below:

# Libraries/Modules import conventions import numpy as np import matplotlib.pyplot as plt # Making the random number generator always generate the same random numbers np.random.seed(10) # Dummy Data x = np.arange(50) y = x + 10 * np.random.randn(50) # scatter() is used for plotting a scatter plot plt.scatter(x, y) # Adding title, xlabel and ylabel plt.title('A Basic Scatter Plot') # Title of the plot plt.xlabel('X-axis') # X-Label plt.ylabel('Y-axis') # Y-Label # show() is used for displaying the plot plt.show()

**Adding size and color to a Matplotlib Scatter Plot**

The scatter() function also allows us to define the size and color of each point being plotted. For this, we need to provide a list/array that contains the size and color of each point in the scatter() function.

# Libraries/Modules import conventions import numpy as np import matplotlib.pyplot as plt # Making the random number generator always generate the same random numbers np.random.seed(10) # Dummy Data x = np.arange(50) y = x + 10 * np.random.randn(50) # Defining sizes and colors sizes = np.abs(np.random.randn(50)) * 100 colors = np.random.randint(0, 50, 50) # scatter() is used for plotting a scatter plot plt.scatter(x, y, s=sizes, c=colors) # Adding title, xlabel and ylabel plt.title('A Colorful Scatter Plot') # Title of the plot plt.xlabel('X-axis') # X-Label plt.ylabel('Y-axis') # Y-Label # show() is used for displaying the plot plt.show()

**Plotting your own data on a Matplotlib Scatter Plot**

The above examples plotted data that were randomly generated to show you how to plot a scatter plot. Now, let us see how you can create your own lists and plot it as a scatter plot in Matplotlib.

# Libraries/Modules import conventions import numpy as np import matplotlib.pyplot as plt # Making the random number generator always generate the same random numbers np.random.seed(10) # Dummy Data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Defining sizes and colors sizes = [112, 380, 100, 12, 60] colors = [4, 20, 11, 3, 1] # scatter() is used for plotting a scatter plot plt.scatter(x, y, s=sizes, c=colors) # Adding title, xlabel and ylabel plt.title('A Colorful Scatter Plot') # Title of the plot plt.xlabel('X-axis') # X-Label plt.ylabel('Y-axis') # Y-Label # show() is used for displaying the plot plt.show()

**Matplotlib Bar Plot – How to make a bar plot in Matplotlib?**

A Matplotlib Bar Plot can be made using the bar() and barh() functions of Matplotlib pyplot.

The bar() function is used to create a vertical Matplotlib Bar Plot and the barh() function is used to create a horizontal Matplotlib Bar Plot.

**Plotting a vertical Matplotlib Bar Plot**

A vertical Matplotlib Bar Plot can be made using the bar() function of Matplotlib pyplot.

For plotting a vertical Matplotlib Bar Plot, we will have to specify the data for the x-axis and y-axis as shown in the example below:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Dummy Data x = ['Year 1', 'Year 2', 'Year 3', 'Year 4','Year 5'] y = [235, 554, 582, 695, 545] # bar() is used for plotting a vertical bar plot plt.bar(x, y) # Adding title, xlabel and ylabel plt.title('A Vertical Bar Plot') # Title of the plot plt.xlabel('X-axis') # X-Label plt.ylabel('Y-axis') # Y-Label # show() is used for displaying the plot plt.show()

**Plotting a stacked vertical Matplotlib Bar Plot**

A stacked vertical Matplotlib Bar Plot can be plotted by plotting more than one vertical bar plot in the same Matplotlib figure.

The following example shows a stacked vertical Matplotlib Bar Plot:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Dummy Data x = ['Year 1', 'Year 2', 'Year 3', 'Year 4','Year 5'] y1 = [235, 554, 582, 695, 545] y2 = [100, 200, 500, 600, 800] width = 0.35 # the width of the bars # Making the plot for y1 list's data and plotting p1 = plt.bar(x, y1, width) # Stacking the y2 list's data at top and plotting p2 = plt.bar(x, y2, width, bottom = y1) # legend() is used for displaying the plot legend plt.legend(['y1','y2']) # Adding title, xlabel and ylabel plt.title('A Stacked Vertical Bar Plot') # Title of the plot plt.xlabel('X-axis') # X-Label plt.ylabel('Y-axis') # Y-Label # show() is used for displaying the plot plt.show()

**Plotting a horizontal Matplotlib Bar Plot**

A horizontal Matplotlib Bar Plot can be made using the barh() function of Matplotlib pyplot.

For plotting a horizontal Matplotlib Bar Plot, we will have to specify the data for the x-axis and y-axis as shown in the example below:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Dummy Data x = ['Year 1', 'Year 2', 'Year 3', 'Year 4','Year 5'] y = [235, 554, 582, 695, 545] # bar() is used for plotting a vertical bar plot plt.barh(x, y) # Adding title, xlabel and ylabel plt.title('A Horizontal Bar Plot') # Title of the plot plt.xlabel('X-axis') # X-Label plt.ylabel('Y-axis') # Y-Label # show() is used for displaying the plot plt.show()

**Plotting a stacked horizontal Matplotlib Bar Plot**

A stacked horizontal Matplotlib Bar Plot can be plotted by plotting more than one horizontal bar plot in the same Matplotlib figure.

The following example shows a stacked horizontal Matplotlib Bar Plot:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Dummy Data x = ['Year 1', 'Year 2', 'Year 3', 'Year 4','Year 5'] y1 = [235, 554, 582, 695, 545] y2 = [100, 200, 500, 600, 800] width = 0.35 # the width of the bars # Making the plot for y1 list's data and plotting p1 = plt.barh(x, y1, width) # Stacking the y2 list's data at top and plotting p2 = plt.barh(x, y2, width, left = y1) # legend() is used for displaying the plot legend plt.legend(['y1','y2']) # Adding title, xlabel and ylabel plt.title('A Stacked Horizontal Bar Plot') # Title of the plot plt.xlabel('X-axis') # X-Label plt.ylabel('Y-axis') # Y-Label # show() is used for displaying the plot plt.show()

**Matplotlib Pie Plot – How to make a pie chart in Matplotlib?**

A Matplotlib Pie Plot can be made using the pie() function of Matplotlib pyplot.

For plotting a horizontal Matplotlib Pie Plot, we will have to specify the data as well as the label associated with it as shown below:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Dummy data label = ['Year 1', 'Year 2', 'Year 3', 'Year 4','Year 5'] values = [235, 695, 554, 550, 545] # pie() is used for plotting a pie chart plt.pie(values, labels = label, startangle = 45) # show() is used for displaying the plot plt.show()

**Exploding a pie out of the Matplotlib Pie Chart **

Whenever we need to highlight important information about a certain pie, we can use the ‘explode’ parameter of a Matplotlib Pie Chart.

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Dummy data label = ['Year 1', 'Year 2', 'Year 3', 'Year 4','Year 5'] values = [235, 695, 554, 550, 545] # Defining a pie that is to explode outside of the pie chart Explode = (0, 0.1, 0, 0,0) # only "explode" the 2nd slice (i.e. 'Year 2') # pie() is used for plotting a pie chart and 'explode' property is used to explode a pie plt.pie(values, labels = label, explode = Explode, startangle = 45) # show() is used for displaying the plot plt.show()

**Matplotlib Histogram Plot – How to make a histogram in Matplotlib?**

A Matplotlib Histogram Plot can be made using the hist() function of Matplotlib pyplot.

For plotting a Matplotlib Histogram Plot, we will have to specify the data for the x-axis and y-axis as shown in the example below:

# Libraries/Modules import conventions import matplotlib.pyplot as plt import numpy as np # Making the random number generator always generate the same random numbers np.random.seed(10) # Preparing random data x = np.random.normal(size = 1000) # hist() is used for plotting a histogram plt.hist(x, density = True, bins = 30) # Adding title, xlabel and ylabel plt.title('A Histogram Plot') # Title of the plot plt.xlabel('X-axis') # X-Label plt.ylabel('Y-axis') # Y-Label # show() is used for displaying the plot plt.show()

In this chapter, we learned to plot the following 2D plots: Matplotlib Line Plot, Matplotlib Scatter Plot, Matplotlib Bar Plot, Matplotlib Pie Plot and Matplotlib Histogram Plot.

In the next chapter, we will learn how to plot 3D plots in Matplotlib. Head over to the next chapter and learn about the different available 3D plots in Matplotlib.

### Chapter IV: Plotting 3D Plots in Matplotlib

In this chapter, you will learn how to plot 3D Plots in Matplotlib.

A 3D plot is a plot where data is plotted on only the x, y and z-axis. 3D plots are mostly used in simulation and modelling and it is important to know how to plot such Matplotlib plots if you are dealing with numerical analysis in three dimensions. The different types of 3D plots covered in this chapter are:

**Matplotlib 3D Space Plot – How to make a 3D space plot in Matplotlib?**

A Matplotlib 3D Space Plot can be made using the projection property of axes() method of Matplotlib pyplot as shown below:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Axes3D is needed for plotting 3D plots from mpl_toolkits.mplot3d import Axes3D # Set projection to 3d in axes() method plt.axes(projection='3d') # show() is used for displaying the plot plt.show()

**Matplotlib 3D Line Plot – How to make a 3D line plot in Matplotlib?**

A Matplotlib 3D Scatter Plot can be made using the plot3D() function of Matplotlib pyplot.

For plotting a Matplotlib 3D Line Plot, we will have to specify the data for the x-axis, y-axis and z-axis as shown in the example below:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Axes3D is needed for plotting 3D plots from mpl_toolkits.mplot3d import Axes3D # Dummy data x = [1, 2, 3, 4, 5] # X-coordinates y = [1, 2, 3, 4, 5] # Y-coordinates z = [4, 10, 20, 5, 3] # Z-ccordinates # Defining figure fig = plt.figure(figsize = (8, 6), dpi = 90) # Making 3D Plot using plot3D() ax = plt.axes(projection = '3d') ax.plot3D(x, y, z) # Setting Axis labels ax.set_xlabel('X-Axis') ax.set_ylabel('Y-Axis') ax.set_zlabel('Z-Axis') # Showing the plot plt.show()

**Matplotlib 3D Scatter Plot – How to make a 3D scatter plot in Matplotlib?**

A Matplotlib 3D Scatter Plot can be made using the scatter3D() function of Matplotlib pyplot.

For plotting a Matplotlib 3D Scatter Plot, we will have to specify the data for the x-axis, y-axis and z-axis as shown in the example below:

# Libraries/Modules import conventions import matplotlib.pyplot as plt # Axes3D is needed for plotting 3D plots from mpl_toolkits.mplot3d import Axes3D # Dummy data x = [1, 2, 3, 4, 5] # X-coordinates y = [1, 2, 3, 4, 5] # Y-coordinates z = [4, 10, 20, 5, 3] # Z-ccordinates # Defining figure fig = plt.figure(figsize = (8, 6), dpi=90) # Making 3D Plot using scatter3D() ax = plt.axes(projection = '3d') ax.scatter3D(x, y, z) # Setting Axis labels ax.set_xlabel('X-Axis') ax.set_ylabel('Y-Axis') ax.set_zlabel('Z-Axis') # Showing the plot plt.show()

In this chapter, we learned to plot three different kinds of 3D plots in Matplotlib: Space, Line and Scatter Plots.

In the next chapter, we will learn how to save both 2D as well as 3D plots in Matplotlib to local storage. Head over to the next chapter and learn how to save plots in Matplotlib.

### Chapter V: Saving Plots in Matplotlib

In the previous chapters, we have learned about how to plot 2D and 3D plots in Matplotlib. In this chapter, we will learn how to save plots in Matplotlib.

**How to save a Matplotlib plot?**

A Matplotlib Plot can be saved using the savefig() function of Matplotlib pyplot.

# Libraries/Modules import conventions import matplotlib.pyplot as plt # For interactive matplotlib sessions, turn on the matplotlib inline mode %matplotlib inline # Dummy Data X = [1, 2, 3, 4] Y = [2, 4, 6, 8] # plot() is used for plotting a line plot plt.plot(X, Y) # Adding title, xlabel and ylabel plt.title('A Basic Line Plot') #Title of the plot plt.xlabel('X-axis') #X-Label plt.ylabel('Y-axis') #Y-Label # Saving the plot plt.savefig('figureName.png') # You can also specify full path to storage

You can find the saved plot in the folder from where you ran the Python script/Jupyter Notebook cell. The image will look like this:

Now we know how to save a plot in Matplotlib.

In the next chapter, we will learn how to work with images in Matplotlib. Head over to the next and final chapter of the Matplotlib Full Course.

### Chapter VI: Working with images in Matplotlib

Matplotlib provides an easy interface to work with images.

**How to read an image in Matplotlib?**

To work with images we first need to import the image data into Numpy arrays using mpimg() function. Then, we can import images using the imread() function of Matplotlib Image.

# Libraries/Modules import conventions import matplotlib.image as mpimg # Read a network/local image and store as numpy array img = mpimg.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Flag_of_Nepal.svg/135px-Flag_of_Nepal.svg.png') # Printing the image type print(type(img))

Output: <class 'numpy.ndarray'>

**How to plot an image in Matplotlib?**

Images can be plotted in Matplotlib with the help of the imshow() function of Matplotlib pyplot as shown in the following example:

# Libraries/Modules import conventions import matplotlib.image as mpimg # Read a network/local image and store as numpy array img = mpimg.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Flag_of_Nepal.svg/135px-Flag_of_Nepal.svg.png') # Show the image stored in the numpy array imgplot = plt.imshow(img)

Since the image is basically stored as pixel values in a NumPy array, we can change the values of the pixels to manipulate the image. The following example changes the color of the image:

# Libraries/Modules import conventions import matplotlib.image as mpimg # Read a network/local image and store as numpy array img = mpimg.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Flag_of_Nepal.svg/135px-Flag_of_Nepal.svg.png') # Apply pseudocolor schemes to image plots manipulated_img = img[:, :, 0] # array slicing operation # Show the image stored in the manipulated numpy array imgplot = plt.imshow(manipulated_img)

Now we know how to read, display and manipulate an image in Matplotlib. For more details on working with images, this Matplotlib guide can be useful.

Also, congratulations on completing this course on Matplotlib!