Comprehensive Imshow Matplotlib Tutorial : Custom a graph

Posted by Marta on December 18, 2020 Viewed 167 times

Learn how to install matplotlib, how to customise your graph: change the font size, the background color, etc and using the imshow function.

Card image cap

In this article will show you how to create a simple chart using the popular matplotlib python library. Additionally, you will understand how you can customize your graph: change the background color, change the font size, change the marker, and include an image using the Matplotlib imshow function.

Change these small details in your charts will give a more professional and polished look. Let’s start installing the Matplotlib module.

How to Install Matplotlib python

The first step to start working with Matplotlib is installing the library. Matplotlib is an external third party library, which means you will need to install it. It is not included in the python installation. You can install this library using pip. To be specific, you will need to run the following command from your terminal:

pip install matplotlib

Once the installation is completed, you can check that the library is ready to be used. To do so, add the following code into a python file, and execute it with python:

#Filename: sample.py
import matplotlib.pyplot as plt

In case the Matplotlib module wasn’t correctly installed you will see the following error:

Traceback (most recent call last):
  File "sample.py", line 1, in <module>
    import matplotlib.pyplot as plt
ModuleNotFoundError: No module named 'matplotlib'

Otherwise, if you installed Matplotlib correctly you shouldn’t see any output.

In case you have several python installations in your machine, make sure you install the Matplotlib module in the same installation you are using to execute your python program.

Create a simple graph

Now that Matplotlib is available, you will see how to create a simple line chart that will visualize the following points:

[2, 5, 3, 51, 2, 4, 5, 23, 4]

See below the code to create a simple graph:

import matplotlib.pyplot as plt

data = [2,5,3,51,2,4,5,23,4]

figure = plt.figure(figsize=(12,6)) # Create a figure

axes1 = plt.subplot(321) # Create an axe within the last figure

axes1.plot(data) # Plot the data

plt.show() # Display the graph

The code above is creating a simple graph. To make the plot first, you need to create a figure and one or more axes. That is the bare minimum. You can see the figure as the canvas that will contain all elements that form the output graph. The axes are the layers where the graph is plotted. One figure can have several axes. Each containing a different chart. The example above has just one ax, with one graph.

Usually, the figure method, plt.figure() is only used when we need multiple panels. If we use only one figure, we can omit this call since a single figure is initiated by default.

The last step is calling the statement plt.show() to display all elements within the figure. See the output graph below:

Add background color Matplotlib

So good so far. We have created a simple graph, so let’s start with the first customization. How could you change the background color of the chart? Here is a scenario where this would be useful. You are planning to show your graph in a presentation, and you would like the graph colors to align with the corporate colors. Or you want one of your charts to have different colors, so it attracts more attention.

You can change the background color by calling the function set_facecolor('green') from the ax. As a parameter, you only need to pass the color you would like to use. See the example below:

import matplotlib.pyplot as plt

data = [2,5,3,51,2,4,5,23,4]

figure = plt.figure(figsize=(12,6)) 

axes1 = plt.subplot(321) 

axes1.set_facecolor('green') # NEW: Change background color

axes1.plot(data, 'white')

plt.show()

Here is the output:

matplotlib

Change the font size Matplotlib

Another often used customization is changing the font size. To do so, you can use the plt.rc(parameters) function. This function allows you to customize all kinds of properties (See the property list), and among them, you can update the font size. Below I will update the font size in our sample graph:

import matplotlib.pyplot as plt

data = [2,5,3,51,2,4,5,23,4]

plt.rc('font',size=25) # NEW: Change font size

figure = plt.figure(figsize=(12,6))
axes1 = plt.subplot(321)
axes1.set_facecolor('green')
axes1.plot(data, 'white')
plt.show() 

Output:

matplotlib

Please note you could also update the font size using the following code line:

plt.rcParams['font.size'] = 5

This line is equivalent to:

plt.rc('font',size=25) 

Update marker matplotlib

The next customization is adding a marker. A marker is a sign that connects two straight lines, which helps to visualize the data and spotting changes in values. They are usually used in line graphs.

We can add markers to our graph by adding an extra parameter to indicate the marker to use.

axes1.plot(data, 'white', marker='o')

See below the output graph:

matplotlib

Using imshow matplotlib

The imshow function is closely related to image manipulation and analysis. Let’s have a closer look at how the imshow function works. The first step is converting the image to a pixel matrix, each pixel containing three values(Red, Blue, Green) that made up the pixel color. Then you can manipulate the image: convert it to greyscale, remove a color, etc. These operations involve modifying the matrix cells. Once you finished the manipulation, you can use the imshow function to render the matrix as if it were an image. Enabling you to visualize your manipulation and double-check you got the expected effect.

Let’s see an easy example of simple image manipulation. Here is the example image I will use:

matplotlib imshow

In this example, I will convert the image to greyscale. Firstly, I will turn the image into a matrix using the imread function:

image = plt.imread('coffee.jpg')
print(image.shape)
print(image[2,2,2])

Output:

(1280, 1920, 3)
81

As you can see above, once the image is in a matrix format, you can access every pixel using its indexes.

The next step is turning the image to greyscale through matrix manipulation.

image_grey = image[:, :, 0]

You can now use the Matplotlib imshow function to render the matrix of pixels as an image and check the manipulation has the expected results.

plt.imshow(image_grey, cmap='gray')
plt.show()

Here is the output:

matplotlib imshow

Perfect, after displaying the matrix as an image, you can confirm the operation applied to the matrix has the expected results.

Add colorbar Matplotlib

A color bar in a graph is a bar that indicates the mapping of data values and colors. Adding a color bar to our graph is quite simple. All you need to do is calling the following method, after rendering the image:

plt.colorbar()

Here is how the code will look like after putting all pieces together:

import matplotlib.pyplot as plt

image = plt.imread('coffee.jpg') # Convert image to pixel matrix

image_grey = image[:, :, 0] # Turn to grayscale

plt.imshow(image_grey, cmap='gray') # Render the matrix

plt.colorbar() # Add the colorbar

plt.show()

Output:

matplotlib imshow

Conclusion

To summarise, we covered how to install the Matplotlib library and create a simple graph, how you can configure it as elements of the graph, like the font, makers, and background color. And last, we have seen how to display pixel data as an image using the Matplotlib imshow function. I hope you find the article useful. Thank you so much for reading and supporting this blog! Happy coding! 🙂

Recommended articles

What is Unit Testing and How to Use it in Python

A beginner’s guide to Big O Notation

Types of Data Structures in Python

How to Create Tkinter Progress Bar and DropDown

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java