Posted by Marta on December 18, 2020 Viewed 3573 times
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.
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.
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:
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:
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()
Please note you could also update the font size using the following code line:
plt.rcParams['font.size'] = 5
This line is equivalent to:
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:
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:
In this example, I will convert the image to greyscale. Firstly, I will turn the image into a matrix using the
image = plt.imread('coffee.jpg') print(image.shape) print(image[2,2,2])
(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:
Perfect, after displaying the matrix as an image, you can confirm the operation applied to the matrix has the expected results.
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:
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()
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! 🙂
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
Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications
Unique lay-out and teaching programming style helping new concepts stick in your memory
Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples
Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.
Excellent read for anyone who already know how to program and want to learn Best Practices
Perfect book for anyone transitioning into the mid/mid-senior developer level
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