Categories

## Using Matplotlib To Draw Line Between Points

In this tutorial, let us learn how to use Matplotlib to draw line between two points. Matplotlib is a Python library package that we can use to draw lines, charts and other plots. It takes in datasets as its input and converts them into plots and graphs. Therefore, it can help us in visualizing and interpreting our datasets is a much more better way.

In order for us to be able to use Matplotlib to draw line between two points, first ensure that Matplotlib is installed on your computer. Once it is confirmed, let us now first create a set of data points that we want to plot.

## Creating dataset for Matplotlib to draw line between points

One of the simplest way for us to create our dataset is by calling Python’s built-in range function.

So, let us now start writing our Python plotting program:

``import matplotlib.pyplot as plt``

In this line of code, we are simply importing the pyplot submodule of the Matplotlib library as plt. Hence from now onwards we can call it by simply calling the plt variable.

Next, let us generate our desired dataset using Python’s range function.

``x = range(5)``

As can be seen here, we are asking the range function to provide us with a sequence of integers from 0 to 4. That is because mentioning an upper limit of 5, we have limited the range between 0 to 5. The step size will also default to 1. As a result, our dataset will now look like this:

``x = [0, 1, 2, 3, 4]``

So now that we have our dataset, its time to plot these values using Matplotlib.

## Using Matplotlib to draw line between points

Since we have already imported Matplotlib’s Pyplot submobule, we can right away start using it to plot our line. Pyplot provides us with a very handy helper function called plot to plot our line.

The general syntax of our plot function looks like this:

``plot([x], y, [fmt], *, data=None, **kwargs)``

As can be seen above, plot takes in an optional x-axis value. However y-axis values are a must for plot function to work. On the other hand, plot function also takes in additional parameters such as an optional [fmt], data etc. You can refer to the official documentation for this function to learn more about how to use it.

However, for our case, we will simply use our dataset as our y-axis parameters. Since x-axis is optional, we can leave it blank. By doing so, Matplotlib will automatically start filling in these values starting with a value of 0 and incrementing it by 1 for each extra intervals. Hence, our code for plotting will simply look like this:

``plt.plot([xi for xi in x])``

What we are doing here is simply passing each of the values of our dataset x as plot functions y-axis parameters.

However, we are still not done here. The code written up until now would have drawn our line connecting the points of data. However, in order for us to be able to display it to the end user, we need to call another function called the “show” function. So, we still need to add this final line of code into our program:

``plt.show()``

With this, we should be able to see a plot drawn by Matplotlib that is drawing a line between our data points. It looks something like this:

## Conclusion

Combining all the above piece of code in a single place will give our final code that looks like below:

``````import matplotlib.pyplot as plt
x = range(5)
plt.plot([xi for xi in x])
plt.show()``````

So this is it! With just these four lines of code, we are able to make use of Matplotlib to draw line between points. I hope this tutorial was pretty straight forward. If you have any more queries or simply want to say hi to me, please leave a comment below! Until next time, ciao!

Categories

## Introduction To Matplotlib – Data Visualization In Python

This article will give you an introduction to Matplotlib Data Visualization In Python. Matplotlib is a data visualization library package written specifically for us to be used with Python. So Matplotlib is usually the preferred Python package to visualize data while working on Machine Learning & Data Science. It helps us in visualizing the data by representing them with the help of plots and charts.

## Brief Introduction To Matplotlib – Data Visualization In Python

We humans are all highly responsive to images than text messages. Images helps us in better visualizing and understanding a situation over interpreting any raw data. So we always wanted a way to represent data through images. If you look at our history, we have always tried to accomplish this in many ways. While I cant go back in time to explain each and every approach, I can quicky give you an historical introduction to Matplotlib. This should help you understand how this package came to be. Why it matters a lot in Python data visualization.

### Historical Introduction To Matplotlib – Data Visualization

In the early days of computer data analysis, data scientists often relied on tools like gnuplot and MATLAB to visualize data. However, the problem here was that they had to do it in two stages. First use programming languages like C or Python scripts to process the data. Then plot the resulting data output using gnuplot or MATLAB.

It was a very cumbersome process to say the least. It also resulted in erroneous calculation at times due to lengthy process. As a result, the scientists were in dire need of a simpler solution to this. This is when Matplotlib – Data Visualization package in Python was born.

This helped scientists to both process the data using Python scripts and also visualize the resulting output using Matplotlib package. Now since the Matplotlib was developed along the lines of MATLAB, it is supporting all the functionalities of MATLAB. Because of this reason, it got embraced by the data scientists over MATLAB pretty quickly.

Now you may be wondering why you should be using Matplotlib over MATLAB. For you to understand and appreciate Matplotlib package, you need to understand some of the benefits it brings over a tool like MATLAB. Discussing the advantages and disadvantages of this library in an article that gives an introduction to Matplotlib is appropirate I believe. This will help you in making appropriate decision while chosing this Python library package.

• Matplotlib Is Open Source – One of the primary advantage of Matplotlib is that it is an open source package. Because of this, you can use it in whatever way you want. You don’t need to pay any money for this tool to anyone. You can also use it for both academic and commerical purposes.
• Written In Python – Yet another benefit of Matplotlib is that it is all written in Python. As you use Python programming language to do data processing, plotting its result in Python again makes it so much more easier.
• Customizable & Extensible – As its written in Python, you will also be able to customize the package (if required) to suit your requirements. In addition to this, you can always extend its functionalities and contribute it back to the open source community. Since Python also has other useful packages, you can also make use of those packages’ functionalities to extend Matplotlib.
• Portable & Cross Platform – Since its written in Python it is easily portable to any system which can run Python. It also works smoothly on Windows, Linux & Mac OS.
• Easy to learn – Because the Python language is much easier to learn, any packages written using this language becomes so much more easier. You will not find Matplotlib any different either when it comes to this.

## Matplotlib Output formats

When we plot any data using Matplotlib, we can get the resulting output plots in two different ways.

The first method is to get the resulting output plots in a new window. This is useful if you want an interactive data output. In this case, your output will continue to display for as long as your program is running.

The second method of output plots you can obtain is by saving them permanently on your computers. In this method, your resulting output will be saved in a file in standard image formats such as PNG, JPG, PDFs etc. This will be very useful to you when you want to share your results with others. You can also make use of this method when you want to generate a lot of output charts or plots programmatically. But in this case, you have one disadvantage. You will not be able to interact with the resulting output like the way you could in the first method. But as I mentioned earlier, if you just want to analyze the results in bulk at a later time, this is still one of the best method to make use of.

So you might be wondering now, what other different formats can you use to save the resulting output. Let me help you right there! So this is the list of file formats supported by Matplotlib that you can use to save your resulting plots:

EPS, JPG, PDF, PNG, PS, SVG

So now you understand the different formats that we can store our outputs in. Next, let me introduce you to another important feature of Matplotlib. It is called Backends and this terminology is something that you should be aware of when working with Matplotlib.

## Introduction To Matplotlib: What Are Backends?

Backends In Matplotlib is a feature using which you can either visualize the output live or store it to analyze them in the future.

As I mentioned in the previous section, we can store the resulting plots in either files or view it live in a new interactive window. Backends simply represent this factor. So from the previous paragraphs we can already realize that there are two types of backends in Matplotlib:

• Hardcopy backend – This is the type of backend where we save the images in a file
• User Interface backend – In this type of backend, we display the resulting output in an interactive output window.

In order to provide us with these two type of backends, Matplotlib makes use of two sub modules called the renderer and the canvas. Let us try to learn more about them to get a better understanding of Matplotlib backends.

### What is a renderer in Matplotlib?

A renderer is a module used by Matplotlib to draw its output plot or the graph. So it is this module that does the actual drawing of our Matplotlib’s output. The standard renderer used by Matplotlib to render its output is called the Anti-Grain Geometry(AGG) renderer.

Now are you wondering what this rendere do? Want to know what is so special about this renderer? This AGG renderer is a high performance renderer. It helps us in getting generating a publication level quality output. It also helps us in obtaining our output with sub pixel accuracy and antialiasing. Is this all sounding too alien of a terminology for you? Then simply know that the AGG renderer helps in getting a high production quality graphs and plots that we can adore about!

Now that we understand about the renderer used by Matplotlib, let us turn our focus towards the second module – canvas

### What Is A Canvas In Matplotlib?

After getting an understanding about renderer, its time for us to learn about the other module – canvas of Matplotlib.

We mentioned that the renderer is responsible for the drawing. But do you know where exactly is this drawing being done at? That is where the canvas module comes into picture. Canvas is the area where the renderer will draw our out plots and graphs. Ok, so who provides this canvas then? Great question!

Canvas in Matplotlib is usually provided by the GUI libraries. So this can be GTK if you are using a Linux machine. Or it can be WX if you are on a Mac OS. On the other hand if you are using Windows machines, these could be coming in from Windows GUI libraries. But these are not all. It could also be coming in from platform agnostic interfaces like QT if you are developing your visualization tools in QT.

So basically we get the canvas from the GUI library we intend to use in our Visualization app.

But do you really need to worry about it? Do you really need to know about canvases and renderers when using Matplotlib? Well, for the most cases, not really. You can simply use Matplotlib’s functions and get away with generating your visualizations. You dont really need to know the underlying aspects of how Matplotlib works to use it. But if you want to be a good visual data scientist, knowing how Matplotlib works under the hood will help you in mastering it. It will also help you in truly appreciating its versatility.

## Conclusion

So that is it. This should give you a good introduction to Matplotlib – data visualization and why you should use it. In the next set of articles, we will learn how to install the library package. We will learn how to make use of it to draw some interesting plots and graphs. So see you there! Until then, have a great learning experience!

If you are interested in using Matplotlib to add text to any image, here is a quick tutorial link describing how you can do this.

Categories

## Python Add Text To An Image Using Matplotlib Library

We can use Python programming language to add text to an image using its Matplotlib library. In this tutorial, we will take a look at the Matplotlib library and learn how to accomplish this. The process of adding text to an image is often also called as annotating text to an image.

## What Is Python Matplotlib library?

Matplotlib is a Python data visualization library that is often used to plot graphs and charts to represent a dataset in a meaningful way. However, we can also use Matlplotlib to do some basic editing on an image file. We can use it to overlay graphical data over an image or plot graphs.

But in this tutorial let us make use of Matlplotlib to add basic text annotation to our image. In other words, we will use Python Matplotlib to add text to our image file.

## Adding Text To An Image Using Python Matplotlib Library

In order to get started, we first need to use an image file over which we would like to add text. In this example, I will make use of this picture of a butterfly that I shot in my garden. This is a simple JPG file that I got by capturing the butterfly image using my Android smartphone’s camera.

This is a 278KB JPG file over which I would like to add an annotated text stating “What A Wondeful World!”. I woud like the text to be Orange in color with a font size of 30 and stylized to be bold. I would also like to place this text at the bottom of the image, somewhere over here:

So enough of theory, let us start writing our Python program to add the text to our image. Fire up your favorite text editor to start writing your code. In my case I use VS Code editor, but you can use any text editor you want.

## Python Program To Add Text To An Image Using Matplotlib

The first line of code we would like to add in our program is:

``import matplotlib.pyplot as plt``

What this line does is that it would import our matlotlib library’s pyplot module into our program. So this is imported as plt so every time we want to make use of it, we would call it by using the plt name.

Next thing we would like to import is the Python Imaging Library (aka PIL)’s Image module. We need to use this module to import the image file (butterfly.jpg) into our program. So this is achieved by using the following piece of code:

``from PIL import Image``

We will then go ahead with importing the butterfly.jpg file into our program using the line:

``img = Image.open("/home/amar/Pictures/butterfly.jpg")``

The Image.open() method will open our file, read its content and store it into the variable img. Notice here again that we have imported the buttefly.jpg file into a new Python variable called img. Because of this from now on wards, we will be able to access the content of this image file by using the img Python variable.

With the image being available, its time to start editing it using Matplotlib library.

The first step in using Matplotlib library is to create a Matplotlib’s figure object, which forms the canvas of our image. All the operations we do from now on will be with respect to this canvas element. We can create Matplotlib’s figure object by using the lines:

``plt.figure(figsize=(12,8))``

Wait a second! What does this line even mean? What does figsize stand for and what values are we passing here? Let us answer these questions first.

### Understanding Figsize Parameter Of Matplotlib’s Figure Object

figsize is a parameter we need to pass to the matplotlib plt module’s figure() method. It allows us to specify the exact width and height of our image.

Therefore when we pass the values (12,8) to this parameter, we are specifying these exact values. These values are expressed in the unit of inches. So when we say (12,8), we are asking the Matplotlib library to draw a figure with a width of 12 inches and a height of 8 inches.

Following this, we will ask Matplotlib library to draw our picture onto the figure‘s canvas by calling imshow fuction as follows:

``plt.imshow(img)``

As a result of the above code, Matplotlib will draw to image onto our figure object. However, it must be noted that it only draws the image to our figure object. But nothing will be displayed to the end user. If we want to display this image, we need to call another Matplotlib function plt.show(). But we do not want to display it yet. Therefore, we will discuss about this function later in the article when we actually make use of it.

So for now we will further move on with our code. As of now we have created a Matplotlib’s figure canvas object, we have opened our image file and drawn this image onto our figure object’s canvas. It is now time to write our intended “What a wonderful world!” text on top of it.

### Adding Text Using Plot’s Text Function

In order for us to write text over an image, Matlplotlib provides us with yet another method, not surprisingly called the text function. So we can access it as part of the plt module. Also, we can find this function’s signature and the parameters it takes in link to its official documentation. With this information, we can finally call the text function to print our string onto the figure object’s canvas like this:

``plt.text(200, 700, "What A Wonderful World!", color="orange", fontdict={"fontsize":30,"fontweight":'bold',"ha":"left", "va":"baseline"})``

From the above code, we can interpret the parameters of plt.text function as follows:

#### X & Y Co-Ordinates Parameter

The first two parameters of this function are the x & y co-ordinates of the image. We set its values to be 200 and 700 so that the string starts from there.

#### Annotation Text Parameter

Following the two co-ordinate parameters is the annotation text paramter. This is the parameter which takes in the text string that we would like to print. We have set it to our string “What A Wonderful World!” that we wanted to add to our image.

#### Text Color Parameter

Following the the text parameter is the color parameter. We use this parameter to set the color of the string. In our case, we have set this to orange color.

#### Font Dict Parameters

Finally, we set the parameters for the type of font to use and its properties. In our case, we are asking Matplotlib library to set the following properties to our text fonts:

• We want to use a font size of 30
• We want the font to be bold
• Next, we want the text’s horizontal alignment to be to its left
• Finally, we also want it to be vertically aligned to its baseline

So with these properties set, we have finally defined the text that we wanted on our canvas. Hence, it is now time to display this image on our screen.

## Displaying Image On Screen Using Matplotlib

This is the final stage of our code. At this point, we want our program to simply display the content of our modified image on our screen. So we will achieve this by using the plt.show() function that we had discussed earlier.

### Using Matplotlib’s Show Function To Display The Image On Screen

The code to display our image on screen is pretty simple

``plt.show()``

We just call the plt.show() function as shown above. This should finally display the image in a new window on our screen.

## Summary Of Python Program To Add Text To Image

So to summarize, our final program in full looks like this:

``````import matplotlib.pyplot as plt
from PIL import Image

img = Image.open("/home/amar/Pictures/butterfly.jpg")
plt.figure(figsize=(12,8))

#Finishes drawing a picture of it. Does not display it.
plt.imshow(img)
plt.text(200, 700, "What A Wonderful World!", color="orange", fontdict={"fontsize":30, "fontweight":'bold', "ha":"left", "va":"baseline"})
#Display the image
plt.show()``````

## How To Save Matplotlib Image To A File

So far we edited the image file and added our own text on top of it. We were also able to display the final result to the end user screen in a separate window.

But what if we wanted to save this image? Can we write the program to save this edited image automatically to a new file? How to achieve this? If these are some of the questions you have running your mind then fret not. Because Matplotlib library comes to our rescue, once again!

To save the image onto a new file, Matplotlib provides us with yet another function called savefig().

### Using Matplotlib’s Savefig Function To Save An Image

Matplotlib provides us with the function savefig() to save our image in a new file. It takes in many parameters which can be seen in this official documentation link. However, for our case, we simply want to save the image to a simple jpg file. So we need not have to use all the parameters defined in that link. We can simply use the following code to save it as a JPG file:

``plt.savefig('/home/amar/Pictures/butterfly_captioned.jpg')``

From the above code, we can see that we used plt.savefig() in its simplest form. We just added a path to the new file and saved it as a jpg file. Yes, the format of the file in which we want it to be saved is given by simply using the appropriate file extension. Matplotlib is intelligent enough to understand this and save it accordingly. Hence, if you wanted to save it as a PNG file, you just need to change the extension to .png. Its that really simple!

So with this, we can finally get our captioned image file as shown below:

So this was a brief tutorial on how to use Python to add text over an image programatically using Matplotlib library. Hope this was easy for you to follow up and understand. I will continue to write more articles on Python and image/video editing libraries in the future including Matplotlib. If you have any more questions or queries regarding this, do let me know in the comment section below. Until next time, ciao!

Categories

## Python Program To Add Two Numbers

In this article, we will look at how to write a Python program to add two numbers. This is a very simple Python program that is suitable for even a beginner in Python programming to work on it for getting hands on practice with Python.

In order to add two numbers in Python program, we need to first break down the problem into the following steps:

## Breakdown of the problem of Adding two numbers

1. Receive the first input number from the user and store it in a Python variable.
2. Receive the second input number from the user and store it in another Python variable.
3. Add the two numbers by adding the two Python variables using a Python statement (Learn about Python statement here)
4. Store the final result in another Python variable called “result”
5. Print the value of the “result” variable.

In the above breakdown of the problem, you will notice that the Python program we will be written in such a way that the two numbers that need to be added will not be hard coded directly into the program itself but instead is written in a generic way such that we prompt the user to enter these two input values every time the Python program to add two numbers is run. This type of programming approach is often called general programming as the program is generic enough to receive any two different values each time it is run.

## Pseudo-code To Add Two Numbers Using Python Programming Language

``````num1 = Receive First Input Number From The User
num1 = Receive Second Input Number From The User
result = (num1) Added to (num2)
Print the (result) on the screen``````

We can see from the above psuedo code that this is a simple program that receives two numbers from the user, adds them and print their results back on the screen. The above pseudo code gives us a nice little framework on how to write our program. The same pseudo-code can now be used to write a program to add two numbers using any programming language and not just Python!

Now that we have our problem broken down and pseudo code written, it is time for us to replace the pseudo code with actual Python programming code instructions.

## Python Program To Add Two Numbers And Print Its Result

Fire up your Python IDLE interpreter and start typing in the code along with me for you to be able to understand this program better:

``````Python 3.5.2 (default, Oct  8 2019, 13:06:37)
[GCC 5.4.0 20160609] on linux
>>>``````

Once in our python interpreter, let us start typing in our Python program commands. The first thing we need to do according to the pseudo code written above is the receive the first input number from our user. In Python program, the instruction code to be used to receive a value from its user is by calling the input() function. Input function will accept a string as its parameter that will be displayed to the program user when the program is run. So, with this knowledge, our first line of the Python program to add two numbers will be:

``````>>> num1 = input('Enter the first number\n')
Enter the first number
10
>>> ``````

As you can see from the above code block, we have used the input() function to prompt our program user with the string “Enter the first number“. We are also saving the value entered by the user to a Python variable called num1.

The input function will then prompt with the above string and wait until the user enters a number. In the above code snippet, I had entered a value of 10 which is now stored in the variable num1.

In a similar way, we will write the next line of code which will prompt the user to enter a second input number that is to be added to the first number. This is achieved with the following piece of code:

``````>>> num2 = input('Enter the second number\n')
Enter the second number
20
>>> ``````

Again over here, I have entered my second number as 20 when prompted.

Now that we have the two numbers in our Python variables num1 and num2, it is time add them to get the final result that we are going to store in our third Python variable called result. This is achieved using the following Python statement:

``````>>> result = int(num1) + int(num2)
>>>``````

So from the above python code, we have now added the numbers num1 and num2 using the Python arithmetic operator “+” and the typecast operator called “int()“. We had to use the typecast operator int because by default all inputs from the user into a python program will be interpreted and stored as a string. We can check this by issuing the following command in the interpreter:

``````>>> print(num1)
10
>>> type(num1)
<class 'str'>
>>> ``````

So, by calling the typecast operator int, we are converting this string value to an integer value.

``````>>> type(int(num1))
<class 'int'>
>>> ``````

finally stored the end result in a new variable called result. Since we have not issued a Python command to print the value of result, nothing gets printed on the IDLE prompt yet. So, the final step is exactly that. To print the value of the result variable onto the screen. This is achieved using another Python function called the print function.

``````>>> print (result)
30
>>>``````

Here is the full program that we can store in a file called add2num.py and run it using the command python3 add2num.py everytime we want to add any two numbers!

``````num1 = input('Enter the first number\n')
num2 = input('Enter the second number\n')
result = int(num1) + int(num2)
print (result)``````

This concludes our Python program to add two numbers.

### Additional Side Notes On Python Programming Language:

Python is an interpreted programming language that gets interpreted and executed on the fly and hence the program written in Python do not need to be compiled like in the case of a C or Java programming language.