Imagine you are creating a mobile app for restaurant management. Your client wants to know what categories of the target audience there are, how much money these groups spend, and when they visit. These statistics are crucial for making correct and timely business decisions.
It is way easier to analyze metrics when they are presented in plots, which clarify dynamics and trends in seconds, rather than in a huge set of data.
Matplotlib is a tool that allows your program to speak in a visual way and turn your data into graphs, pie charts, bar charts, and more. You only need a few lines of code to draw a histogram. The tool effectively makes you an artist, even if you can’t draw a simple table!
What is Matplotlib in simple terms?
Before we get into Matplotlib with Python, let’s remember that Python is one of the most widely used and easy-to-learn programming languages in the world. This makes it ideal for starting a career in coding. Thanks to its more than 30-year history and popularity, it amassed numerous libraries that can perform many functions with built-in and easy-to-use tools.
Matplotlib is one such tool. It is a library that covers almost all of a coder’s visualization needs. It provides solutions for pictures, graphs, pie charts, and tables ― all the way through to gifs and other kinds of animated content.
What does Matplotlib do?
Management and science are about data. Working with data requires visualization to see correlations and trends. In business, the dynamics of key parameters are often all that’s needed for tracking performance and making decisions. A glance at a bar graph, for example, will reveal whether there are unusual highs and lows worth a closer look at. With the help of such a graph, only seconds are needed to understand, for example, what day has the maximum number of visitors to a restaurant. You would need much more time and effort to analyze this data in the form of a table.
That’s why data visualization is not just a trend, but a necessity for common software such as Excel, as well as special programs for data analytics. Visualization is a language equally understood by both data scientists and other managers involved in making decisions.
Let's go back to the example we started with. If you were building a mobile application for restaurant management, you would need to track foot traffic, audience categories, and spending habits to gain a comprehensive understanding of revenue streams.
Matplotlib can help us demonstrate the key metrics and dynamics of a restaurant for a particular week using the following tools.
Let’s take several visitors for each day of the week in order to draw a plot that helps us see the dynamics for that week. Below are three examples of different plots to show what Matplotlib is capable of.
This is a simple line plot demonstrating the number of visitors broken down by days. We added random data to illustrate how Matplotlib functions work.
The following pie chart is about target audiences. A restaurant needs to see who its visitors are in order to focus its marketing campaigns and fine-tune its products. In this case, we see the week’s target audience by age.
This pie chart will help us with the percentage of visitor groups broken down by age bracket.
A scatter plot is one of Matplotlib's most useful and most implemented tools. It enables you to see correlations between several metrics and get a clear picture of how the business functions in just a minute. In the restaurant’s case, we have the number of persons from each of the age groups (the pie chart) and the money each group spent during the week. So an automatically created scatter plot provides insight into which of the groups was the most profitable.
You might ask how we calculated who spent how many dollars in case we’re dealing with a group of visitors — let’s say, a family, consisting of persons of varying ages. Well, that’s a task that data scientists like to tackle. In case every person paid for themselves, the calculation is rather easy. And in case there was a single-payer for the group, his or her age was taken for the calculation.
One glance at this scatter plot hints that the senior and 45–60 groups bring in the most money.
How to use Matplotlib
In some frameworks and applications such as Google Colab or Jupyter Notebook, Matplotlib is installed.
If it is not, you use the command
python -mpip install -U matplotlib
and then import it when writing code by typing
from matplotlib import pyplot as pltor
import matplotlib.pyplot as plt
“plt” нere is a PyPlot module that creates plots.
Looking at any mobile app for weather or, say, the National Hockey League’s standings, you may think that a coder’s work does require some drawing skill, or at least an artistic mind. Otherwise, how do coders manage to draw all these plots?
The answer is easy ― as all these “paintings” are pure code.
Let’s look at the code of the most complicated plot of the ones we did above for the restaurant management app, the scatter plot. Here's what it looks like in Google Collab, a code editor where you can see the result in real-time:
Using Matplotlib is quite easy for a number of reasons. First of all, most businesses don’t require complicated plots and other visual elements. The three plots from above are what’s enough in many cases. And, as you see, even the most complicated of these examples don’t require a lot of lines or advanced skills. A Python junior is perfectly capable of performing the task.
Secondly, there is plenty of written code that you can take as a basis for your own. That’s of special convenience when you need something rather difficult or something you’ve never done. Again, it’s rare that you will face a task requiring a very sophisticated skill. After all, Matplotlib’s guide is comprehensive.
One very useful Matplotlib feature
Information is often used in reports, presentations, and letters. A quick and convenient export of plots is necessary for any projects dealing with figures. We often need to share files by emailing them or putting them into a cloud so that others could use them too. It’s important that our coworkers, clients, friends, and others not just have the ability to look at plots, but also to further transform them for reports, presentations and so on.
With the number of gadgets and file formats constantly growing, it is sometimes difficult to find an appropriate file format that could run on both, your smartphone and your client’s desktop.
Matplotlib takes care of that. It allows you to conveniently export a plot in any format. The library deals with all currently used types, be it gif, png, jpeg, mp4, avi, pdf, or mov. To use that, you need the function savefig() to save a plot in the formats you need. This function also specifies other file parameters, for example, the path to save the file on your machine for sending it by email, or the file’s print resolution.
Some other very useful Matplotlib features
Matplotlib not only provides static visualization but can also create changeable elements. Concerning our example, the restaurant management app's changeable elements may be needed, as restaurant managers may use different smartphones with varying screen sizes.
You can commit various visualization effects to plots in your project, such as shadows, dotted lines, or 3D.
Besides that, there is a trend for moving elements like gifs, etc. Matplotlib can help there too.
There is more to Matplotlib than just plots and animations, however. To give you an idea for further exploration of the library’s capabilities, we’d like to mention the Cartopy module, which provides a vast spectrum of methods for depicting cartographic information. You may need to create a map with country borders displayed, or, for example, turn a “flat” map, which we usually see on a screen, into a 3D figure.
Matplotlib is comprehensively described in its guide, which outlines all the functions and covers almost every visualization scenario you may require for your project.
However, as with every popular and well-developed library, Matplotlib has a great and extensive community that contributes to its tools and their implementation. The Discord community shares a lot of solutions and ideas on how to best use the library’s capabilities.
You can always ask a question there that’s not contained in the library’s guide or head over to StackOverflow to find a proper answer or a piece of code in minutes. Sharing information and assistance is widely accepted in the coding community, which makes the work easier, faster, and more enjoyable.
The creation of visual elements may seem difficult, but in reality, is not that complicated. You will find it simpler when you start coding and using Matplotlib to let Python programs speak through images. In fact, even rather extensive plots require only a few lines of code. And all you need to do is a thorough knowledge of Python and the Matplotlib guide ― no design or art lessons are necessary!
Learning Python and Matplotlib at the same time is more efficient than learning them separately. You save time and quickly strengthen your skills.
Python has lots of visualization libraries, most of which are built on Matplotlib. So, by learning Matplotlib first, you're learning a common base for many other tools. TripleTen’s Data Science Bootcamp teaches Python, Matplotlib, and numerous other tools for a bright career in data science. In 13 weeks you will master the skills to become a data scientist with a median salary of $89,300. Take the first step on the road to your future career today!