Python Init Function Example, Syntax & Best Practices

In this article, we will take a look at the Python Init Function using an example. At first, we learn about it’s syntax and how we can use it. But once we are comfortable with it, we will then learn the best practices to use when we want to call it!

So, does this plan sound good? Yes? Then let’s do it! 😉

Python Init Function Example and its syntax
Python Init Function Example and its syntax explained in 5 minutes

What Is The Syntax Of Python Init Function?

So first, let us start with how the syntax of a Python Init function looks like. Now, for us to know about it, we will have to take a look at the Python’s official document. From this, we now get to know that the init function is a method of a class and it looks like:

def __init__(self)

From the above code, we can see that the init function takes at least one argument. This is called as ‘self‘ and it has got a special meaning to it. But before we learn about it, let us first know how Python’s Class works.

You see, in Python a Class can have many methods in it. But it will have one method in it for sure. It is called the init() method. Now this method will be present in a Python Class even if you have not declared it yourself!

So, in other words, init() is a function that you will always find in any Class of Python. If you declared it yourself, it is an explicit init() function. But if you did not, it will be an implicit init() function!

Alright, so we now that an init() function is always present in any Python Class, what does it do? We will answer this question next!

Why do we need an init() function in Python?

So to answer this, we need you to have some knowledge about Object Oriented Programming (OOP). So if you are not so familiar with it, please go and learn about constructors in OOP. But for now, I will assume that you do know about OOP.

So as you know in OOP, we have a constructor method in every Class. So whenever we create an object using a Class, its constructor method will get called. Right?

In the same way, in Python the init function acts as a constructor. So it will get called whenever we create a Python’s Class object.

So this is why I said that the init() function is always present in a Python Class. So, the syntax of the init() that you saw above is how it looks like when it is implicit.

What does the self parameter do?

In order to answer this, let us take a look at the syntax once again

class Test:
    def __init__(self)

Here, we are looking at the code of an example Python class called Test. So here we can see that the init function has one argument called self.

Now, in order to for us to understand what this self argument does, let us first create an object of the Test class type.

t = Test()

So in the above code, we created a new object instance of the Test class. Now, as soon as this code runs, the init() function of the Test class will get called. But what is getting passed as the self argument here the variable t itself.

So, we now see that the self argument of the init() function points to the instance of the object itself!

Are you clear until now? Good! Then let us now look into an example of Python Init() function.

Python Init Function Example

So, let us take a look at this Python Init function example code

class Point:
    def __init__(self, x, y):
        _x = x
        _y = y

p = Point(1,2)

From the above code, we can see that we now have a new Class called Point. We also have an init() function that we have defined explicitly. This init() function takes in three arguments self, x & y.

Is it all clear? Good!

So we can quickly see the advantage of using init() function here. With the help of this function, we are able to set the initial values of x & y variables!

So when we created an instance of Point class using the code:

p = Point(1,2)

we were able to set the p object’s x & y values to 1 & 2 right away!

So, if things are clear until this point, we will then move on to the last part of this article.

Best Practices With Python Init Function

So here is a list of best practices you should follow when writing an init function:

  • Always use Init() function to initialize values to object parameters
  • Reduce the number of parameters passed to the init() if possible. Do not over use it.
  • Keep the init() function simple. Do not abuse it!


So that is about it! That is all you need to know about Python init() function. We have discussed everything there is to know about Python’s init() function with an example. We also went through the best practice we should follow when making use of it.

So with this, I will end this article here. If you still have any more questions, please ask it in the comment section below!

Know the difference between an expression Vs statement in Python

So until next time, have a nice day! 🙂


Buy Arduino Nano Online At A Low Price

In this article, we will learn how you can buy an Arduino Nano online. We will learn how to buy it online in India at a low price. But before we do that, let us first learn what an Arduino Nano is in the first place. So are you ready to dive in? Then let us go!

What Is An Arduino Nano Board?

If you are still a beginner in the embedded world, chances are you may have not heard about Arduino Nano until now. So what is it?

Well, the Arduino Nano is a small computer board that one can buy to learn more about computers. It is a computer on a single PCB board that contains all the circuitry needed to run the software code on it.

Oh wait a second here! So we are learning that it is a single board computer, right? Cool! But then you may be wondering how does this Arduino Nano look like?

I am glad you asked this question! Here is a picture of an Arduino Nano board I will share with you for your pleasure. Take a look at it.

Arduino Nano Board Available To Buy Online
Arduino Nano Board You Can Buy Online

Woah! That is one weird looking single board computer out there! But what are all those pins coming out of it?! Looks scary isn’t it?

But don’t worry. Even though the Arduino Nano board looks like that, it is actually easy to use. There are many tutorials we have that will teach how to use it. So learning how to work with it will never be a problem at all.

So with this introduction to Arduino Nano, it is time for us to move on to know how we can buy it online.

How To Buy Arduino Nano Online?

There are many sellers who are selling the Arduino Nano hardware board. They are selling these Arduino Nano boards in online stores as well as in the offline stores. However, when you try to buy the Arduino Nano board, you will realize that the price differs a lot from one seller to another!

Now this is happening because there they are all not original Arduino boards. You see, the thing is Arduino boards are all launched as open source hardware boards. So, their circuit as well as their board designs are all available for free for anyone to use.

So, what happened because of this is that there are many Arduino Nano clones as well. Since these Arduino clones are coming from China, they will be of cheaper cost.

So in that case, who is the original manufacturer of Arduino Nano?

Arduino is the company that designs and manufactures the original Arduino boards. But as this company is from Italy, the products it makes are costlier than their clones.

So now this begs us with our next question which is:

Who manufactures the Arduino clones?

Most of the Arduino clones manufacturers are from China. So since the manufacturing cost of these boards are cheaper in China as compared to Italy, the clones are always cheaper.

So here is the real reason then! This clearly tells us why we see so much difference in the price for the same Arduino Nano boards across different online websites!

So depending on how much you can spend, decide which Arduino Nano board you want to go for.

What is the difference between an original Arduino Nano Vs a Nano clone?

Now as I told earlier, both the original and the cloned Nano boards use the same circuit design. So nothing is different over here. But there is one difference between the two. And this difference is in terms of the quality of components used.

So if you want a higher quality board, you pay more and go for original Nano module. But on the other hand, if you want to spend less, just go for a Nano clone. It really doesn’t matter at all. Trust me!

What Is The Price Of Arduino Nano Online In India?

If you are from India, you can buy the original Arduino Nano online at a low price of Rs.1449. But if you are OK to buy a cheap Arduino Nano clone, you can buy it at a low cost of Rs.200!

What Is The Price Of Arduino Nano Online In The US?

In the US, you can buy an original Arduino Nano at a cost of $22.00. But on the other hand, a cloned Arduino Nano will only cost you around $9! It’s as cheap as that!

What Is The Online Price Of Arduino Nano In The UK?

But if you are in the UK, you can buy the Nano board at just GBP20!

Have you looked at the new Arduino Portenta?


So there you have it. We just looked into the price of an Arduino Nano in 3 different regions. I also explained to you why its price changes so much when you want to buy it online. It is because of the clones that has reduced the price of these boards.

I hope you have got what you were looking for in this article. If you still have any more questions on it, ask me right away and I will answer you.

I hope you will have fun working with them. These are the best things you can work on to gain good knowledge. It is also one the best hobby that will keep you busy for some time! So enjoy with your new toys! Until next time, ciao! 🙂


Arduino Portenta Technical Specification & Price

In this article, we will take a look at the technical specification of Arduino Portenta. But along with this, we will also learn about its price during its release date.

Just today, Arduino launched its new product called “Arduino Portenta” at CES 2020 show in Las Vegas. So far from what I have learnt, it is an IoT device. Which means that you can use it to connect things in your house to the internet!

But not just that! The company is also claiming that we can use Arduino Portenta even in industrial applications.

Ok, all this is fine. But why do we even need this device in the first place? To answer this question, we first need to discuss the technical details of Arduino Portenta. So let us first do that!

Arduino Portenta H7 Technical Specification

Arduino Portenta H7 Processor

The Arduino Portenta H7 is driven by the ST Microelectronics’ STM32H747XI low power processor. This processor is made up of dual ARM Cortex cores.

The first ARM core present in it is a Cortex-M7 running at 480 MHz. On the other hand, the second ARM core is made up of Cortex-M4 and running at 240 MHz. So with these two cores together, this ARM processor is able to run Arduino code, Python and Javascript code as well!

Now this is very interesting! Since it can run Javascript, many of the web developers will be able to work on it!

What OS does the Portenta H7 run?

We got to know that Portenta H7 is running on Arm’s Mbed OS! This is amazing! Being able to run an embedded operating system will mean we can make use of all the resources efficiently!

What type of connectivity does the Portenta H7 have?

Arduino mentioned that they support all the standard connectivity we can expect. So that means it has support for Bluetooth Low Energy, WiFi and LTE as well!

UPDATE On The Radio Module Of Arduino Portenta

We just got to know that the Arduino Portenta features a Murata 1DX dual WiFi 802.11 chipset. This chipset also has support for Bluetooth 5.1 BR/EDR/LE!

Arduino Portenta H7 with Technical Specification and release date
Arduino Portenta H7 IoT Module

What GPU Type Can We Find In Arduino Portenta H7?

The technical specification of the Arduino Portenta H7 mentions that it features a Chrom-ART graphical hardware accelerator.

What does the technical specification say about Timers in Arduino Portenta H7?

Alright guys. We know that in order for us to work with any time sensitive operation we need support of timers. So how does we score here? Well luckily on the timer front, the board has a total of 22 watchdogs and general purpose timers in it. So we have all the room to take its advantages!

But what about the UART ports in Portenta H7?

Ofcourse even though we have moved towards wireless connectivity, we still need good old UART ports for many reasons. So how do we fare on this front? Well the Arduino Portenta H7 strikes back once again! It is exposing a total of 4 UART Ports. And among these 4 ports, two of the UART ports have support for flow control.

How many connectors are exposed on the Arduino Portenta H7 board?

The Arduino Portenta H7 board exposes a total of 160 pin connectors. These connectors are grouped into two 80 pin sets and will expose all the peripherals present in the Portenta H7 board.

What type of USB does Arduino Portenta H7 support?

On the USB front, Arduino Portenta H7 exposes a USB Type C connector. This USB-C connector has support for host/device, displayPort out. It can operate at high speed or full speed USB protocol configuration. The Portenta H7 USB-C also supports Power delivery.

What is the operating temperature range of Arduino Portenta H7?

Arduino Portenta H7 can operate at a temperature range lying between -40 °C to +85 °C when running without the wireless module. But with the wireless module, Portenta H7 can operate in the temperature zone of  -10 °C to +55 °C.

What is the operating voltage of Arduino Portenta H7 acccording to its technical specification?

Arduino Portenta H7 works at 3.3 Volts.

What type of battery does Portenta H7 support?

The Arduino Portenta H7 runs on a Li-Po battery. This battery has an operating voltage of 3.7 Volts and a discharge rating of 7000mAh.

Does Arduino Portenta H7 support an SD Card?

Yes it does! The Portenta board has an SD card interface support. However, this SD Card interface is available only through an expansion port. So that is a bit of a bummer! 🙁

But now that we know the Arduino Portenta H7 technical specification, when will it Release?

I know I know. No matter how good the device is, we cannot take advantage of it until it gets in our hands, right? So we can understand when you are eager to know when this module is going to be released.

So from what we got to know, Arduino Portenta H7 is already made availale for beta testers. But it is going to become available for everyone by February 2020! Guys, that means we are just a month away from getting hold of it in our hands!

Now that we went through it’s technical specification, What will be the price of Arduino Portenta H7?

Cool! So now that we know we can get hold of Portenta by next month, our next question is obviously this.

How much it is going to cost?

Unfortunately at this point in time, I could not find an answer (Look for update at the end of this article for pricing information) for this. So I will continue to look out for this information. Once I find it, I will revisit this article and update it with the latest price. But until then, I can only leave you guessing about it.

But on the other hand, if you have any idea about it, let me know in the comments below. And not just that, if you have any other information about Portenta H7 in general that I have missed here, do let me know. In this way, I can update this article in the future for others to benefit out of it.

So there you have it. I have shared all the information I had about Arduino Portenta H7 here. While for me this device is something I am eagerly looking forward to, I wish it had a better name. Somehow for me, the name Portenta H7 is becoming difficult to remember. But may be it is just me I guess.

So any case, I will end this article at this point. So see you guys again in the next article. Until then, take care! 🙂

Latest Update On Arduino Portenta Price

We just got to know that Arduino Portenta will cost USD 99.90 + Tax.

So the cost of Arduino Portenta in the US will be $100 + taxes

The cost of Arduino Portenta in the UK will be around GBP 77 + taxes

The cost of Arduino Portenta in the European countries will be around 90 + taxes Euros

And finally the cost of Arduino Portenta in India will be around Rs.72000 + taxes


5 Best Domain Name Ideas For Food Blog

Here is a list of domain name ideas you can use to start your own food blog. Now we know that if you are a food blogger looking to start your own blog, then finding a suitable name is a challenge. So to help you on this, we have come up with a short list of domain names that you can use for your blogs.

We will go through each of these blog domain names and discuss its advantages. These are all domain names best suitable for a food blog and available for registration. So, using one of these names should give a meaningful character to your blog.

5 best domain name ideas for food blog

What do we need to look for when coming up with a blog name?

There are lots of challenges we need to overcome when we are trying to come up with a name for a food blog. So let us discuss this first. Now since this is a new food blog, your visitors will be unfamiliar with it. Therefore, you need to have a brand name that is catchy, creative and easy to remember. In this way, when your visitor visits your website, it’s name will get registered in his mind.

Here is a little exercise for you

I want you to recollect how many brands and names you came across today? Every brand names you had come across the entire day, I want you to try and recollect them. Done? Now tell me, how many of those names were you already familiar with? And how many “new” brand names did you come across today?

Did you make a list of it?

So here is the thing. Most of the familiar names you recollected were because of their extensive marketing. They would have been promoting their brand names regularly and as a result, it has become a house hold name now. And that is the reason you were quickly able to recollect most of the well known brands. But you can’t take this path because you need to spend a lot of money for that. Because advertising needs money.

But on the other hand, let us look into your list of the new brand names you had came across. It might not be a long list. But it is still something you were able to recollect and write it down. So that is by itself surprising isn’t it?

But can you realize why you were able to recollect that new brand name? The answer will most likely be because it was easy, memorable and creative! So these are the same 3 things I had listed earlier that you need to use while coming up on your own food blog’s name! Correct?

So you saw the pattern here. You now know exactly what you need to do come up with a successful brand and domain name.

So with this in mind, let us start going through each one of the domain name ideas that you can use right away for your food blog.

Domain Name Idea For Food Blog #1

Buy Domain Name:

Now this is one of the interesting domain name ideas for food blog. Because it is simple, cheesy and easy to remember as well.

Also everyone who has been using an automobile will be very familiar with the term fossil. It is literally how the fuel is obtained for the said automobile.

Now, if we consider humans to be like automobile, what is the fuel we need? Yes, you got it right. It is the food!

So combining the word food with its intended activity as a fuel for body, makes so much sense! Also, since this is a .com domain name, it is easy to remember!

Domain Name Idea For Food Blog #2

Buy Domain Name:

Now this ia very unique domain name idea for a food blog to use. We are all familiar with how a car is made right? It is made up of individual parts that gets assembled in a factory. So the end product – the car is assembled in a factory. Now just like that, even we assemble our food by making use of its ingredients.

So when you use a name like for your food blog, it signals the process of the preparation of food. So what do you guys think of this name? Doesn’t it sound cheeky, professional and still easy to remember? 😉

Food Blog Domain Name Idea #3

Buy Domain Name:

Now far some reason, you don’t want to use keyword like food for your domain name, we have an alternative for that. You can simply use this new domain name

I think by now you are already able to figure out how this is a good name. If we simply break the domain name of this food blog, we get three words plates + of + aroma.

Aroma, if you are not a native English speaker simply means smell. So when I say plates of aroma, I simply mean delicious smelling food in a plate. See again, this domain name is very easy to remember. You are making your website’s visitor imagine a plate of food. And this food is something that is delicious and best smelling. And this food is served on a plate for you to eat up!

Now that is a sight to remember isn’t it. Also, everytime he comes into a similar kind of situation for real, he will remember youf blog!

Win-win for you if you use this domain name for your food blog, isn’t it? 😉

Food Blogger Domain Name Idea #4

Buy Domain Name:

Now this is a domain name that is on point! It clearly describes you, a food blogger’s mastery over your food art.

This domain name is simply a combination of two words meal and artist. Here, the word meal simply tells that the subject is about food. On the other hand, the word artist would mean that you are an expert in it.

Also, since this domain name uses two most familiar words, anyone will be able to remember it easily.

Domain Name Idea For A Food Blog #5

Buy Domain Name:

So this is an interesting domain name for a food blog, right? What we are doing here is to combine two food items. Eggs and Potatoes and forming a domain name out of it. Now since egg and potato scramble is a common food item everywhere, it is easier to remember.

Aslo, it comes as a surprise to us that this domain is still available in a .com extension!

So, if you are just starting out a new blog and unsure about a name, this is the one you should mostly be picking up!


So, these were the top 5 domain names you can use to create your food blog. As a food blogger, the domain name ideas you use should match the content you plan to post in the blog. So make sure that you pick the right name depending on what you plan to write.

Also as a food blogger, your reputation in the social media only increases if you can come up with innovative recipes. So, keep these things in mind when registering a domain name for your website.

So with that, I will end this article now. Hope you liked some of the domain names I have listed here. If you still have any questions or suggestions, do let me know in the comments below.


Best Android MP3 Tag Editor Apps In 2020

In this article, we will take a look the top MP3 Tag editor apps for Android. These are the best MP3 ID3 Tag editor Android apps we can find in 2020. Since most of the Music players in Android cannot edit these MP3 tags, we need to use these apps.

But before we start listing the best Android MP3 ID3 Tag editor apps, let us first know what these tags are.

What Is An MP3 ID3 Tag?

So here is the thing. We are all familiar with an MP3 file, right? It is a file format we use to save our music. By saving the music in an MP3 file, we can playback this music over and over again in the future using MP3 players.

While this is all sounding good enough, there is still one feature missing in an MP3 file. While an MP3 file can play back the music, it cannot tell us any information about it. So in other words, MP3 files could not store any details about the album itself. So some of the information like it’s artist name, song title, duration etc is lost.

Now in order to avoid this, MP3 format developers came up with a unique idea. They decided to append the MP3 file with tags called ID3 tags.

What does an ID3 tag do?

It simply holds additional information for an MP3 file. This can be the artist name, duration, cover art etc. So, ID3 tag is simply a word play. It is a short hand for ID tags for MP3 files!

How can we edit an ID3 tag?

So now that we know what ID3 tag does, let us see how to edit them. Usually, if you are using a computer like PC or a Mac, there are many applications we can use to edit them. Some of these desktop applications include MP3Tag, PuddleTag or Easytag.

However, what can we do if you do not have a PC? Can we use our Android smartphones to edit the ID3 tag? Are there such Android MP3 Tag editor apps in the Play store? Let us find out!

Best Android MP3 Tag Editor Apps In 2020

So if you are using an Android smartphone, we can use any of the following Android MP3 tag editor apps. By using these Android apps we can not only edit the metadata of the MP3 file, but also add cover arts to it. So let us look intothese Android ID3 tag editor apps one by one.

Automatic Tag Editor App For Android

Automatic Tag Editor is one of the most popular app we can find in the Android Play Store. Using this app, you can edit the ID3 tag with just a few taps. It auto suggests most the tags by looking into your music library. So you can pick those tags that closely matches your music file.

Android AutoTag Mp3 Tag Editor
Android Mp3 AutoTag Editor

This app claims that you can pick tags for a song in under 5 seconds! But not only this. Automatic Tag Editor app can also be used to change the cover art for your album.

This Android app is one of the most popular app we could find in this category. It did what it claimed (although 5s per song is a bit cheesy) without any problem when we used it. And with 1M+ installations, it definitely is a successful app we could find out there.

Download Automatic Tag Editor App Here

AutoTagger – Automatic & Batch Music Tag Editor

AutoTagger is another Android MP3 tag editor app that you can use. This app also does what Automatic Tag editor android app claims to do. So AutoTagger can help you in tagging MP3 files with artist name, song title, duration etc.

Android Mp3 Tag Editor
AutoTagger Android Mp3 Tag Editor

Along with this, the Android AutoTagger app can also be used to change album cover art. While it provides us with HD cover images, we can also use our own cover art images! So that is a great feature to have, right?

The AutoTagger Android app is available as a freemium app. So the basic features are free. But if you want to do something professionally, you will have to go for its premium version.

Download AutoTagger App Here

So there you have it. These are some of the best Android MP3 ID3 Tag Editor Apps that we could find that you can use in 2020.

If you are using these apps, do let us know about your experience by leaving a comment below. Or if you have any other Android tag editor app suggestion for us? Do let us know!


Huawei P40 Pro Specification, Release Date & Price In India

We just came across some leaked information on Huawei P40 Pro specification. We got to know some details on its specification, release date and price in India. Since it is one of the most awaited Android smartphone, we thought we would write about it here.

Huawei P40 Pro Specification

What OS Does Huawei P40 Pro Use?

So Huawei P40 Pro is an upcoming smartphone that runs on Android OS. But more specifically, it will be running Android 10 OS. However, it will not be a pure Android 10 OS, but come with EMUI skin running on top of it.

But Wont Run Google Services!

But what is even more interesting is the news that it will not have Google services running on it. Instead, it will be replaced by Hauwei Mobile Services.

What Processor Does Huawei P4 Pro Have?

Moving further with Huawei P40 Pro Specification, let us look at its processor. We have learnt that Huawei P40 Pro will use Kirin 990 SoC.

Huawei P4 Pro Smartphone Specification
Huawei Logo

Huawei itself is the manufacturer of this SoC. Kirin 990 supports 5G, so that is good as most of the operators will be moving to 5G soon.

What Is The Display Size Of Huawei P40 Pro?

The next item in Huawei P40 Pro specification to look at is its display. From what we know so far, it looks like Huawei has taken a good decision over here too. Instead of going crazy on the display size, they have kept its size at 6.5 inches. It is also said that the screen will curve on its edges, giving it a premium look. It will also have a 120Hz refresh rate.

What Is The Battery Capacity Of Huawei P4 Pro?

On the battery front, the leaks says that Huawei P4 Pro could have a battery capacity of up to 5500 mAh. We can be pretty sure that it will also include a super charger for fast charging.

What USB Connector Type Will Huawei P4 Pro Sport?

The leaks tell us that this Android smartphone will sport the latest USB Type-C connector. This is really good, because we dont have to worry about the problems we had with older USB types anymore, If you are not sure what benefis USB Type-C brings in, read our earlier article that explains this in detail.

What About It’s Camera?

We know that you have been waiting for an answer to this question. From the information we have gathered so far, we think that it will have a penta-camera setup. We are told that it will have a 20MP ultra-wide angle camera, a 12MP periscopic camera, a dedicated macro camera and a 3D camera. While this all looks nice, we will need another confirmation about it for it to be sure. So fingers crossed at that.

Hauwei P40 Pro Release Date

So that was all that we know about the Huawei P40 Pro Specification. But moving beyond that, let us look at its release date. We learn that P40 Pro will be launched around March 2020. So, not too far away if you were planning to buy a new smartphone anytime soon.

Huawei P40 Pro Price In India

So finally, let us discuss about P40 Pro price now. We are getting an estimated price of this Android smartphone in India. We think that Huawei P40 Pro will retail at a price of around Rs.74,000. Please note that this is just a speculated price. We will get to know its real price only during it’s launch time. So take this price with a grain of salt.


So that was about Huawei P40 Pro specification, price and release date. We will further continue to update this article as and when more information becomes available. So watch out this place for more. But until then, take care! 🙂


How To Change Line Color In Matplotlib

When we draw the lines in Matplotlib, it uses default colors to draw the plot. However, what if we want to change the line color in Matplotlib to our liking? Is there a way we can do it? In this article, we will try and learn how to do just this.

How To Draw Lines In Matplotlib

But before we change the line color, we need to know how to draw the lines in Matplotlib. We need to know what functions to use and in what order to call them. But lucky enough, we already have an article that explains how to do just this.

So if we simply follow the linked article, we get a graph that looks like this:

Matplotlib multiple lines same graph
Matplotlib plot with multiple lines

And we got the above plot by running the following code:

import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])

So just to help you better, let us go through the code once again.

The second line in the code is how we get a set of values between 1 to 10 stored into our array x.

Now, the next three lines of code is how we draw the lines using Matplotlib. The plot function is the one responsible to draw our lines. Since this function is called 3 times, we get 3 lines drawn.

Also, you can see that the plot function is taking x values as its input parameters. Now since we want 3 different lines, we cant pass the same value of x in all three plot() function calls. Therefore, we multiplied x with 1, 2 & 3 respectively for each of the three lines. So that is how we got the above Matplotlib plot with three lines.

But wait a second! How are the colors of these three lines set? How are the three lines drawn in different colors? Who made them do it?

Well the answer is, it was all done by Matplotlib. Because the default behavior of Matplotlib is to draw lines in different colors if color is not specified. So now you know it!

With this, let us now see how we can change the color of these lines.

How To Change Line Color In Matplotlib

Ok so how do we go about changing colors in Matplotlib? Can we get any help from Matplotlib here?

Luckily, yes! Since changing a line’s color is such a basic requirement that Matplotlib has included it as part of the plot() function itself!

Yes, you read that right. We can change the color of our line by using our plot() function itself. So far we have used plot() function by passing only parameter x & y. However, it also supports another parameter that we can use to set the color of the line it draws. So if we pass a third parameter for the color we want, it draws line using that color! Cool, isn’t it?!

So this begs us the next question. What type of values ca we pass to specify a color to the plot() function?

Different Color Parameter Values Accepted By The Plot Function

The Matplotlib’s plot() function supports 3 different types of parameter values:

1. Predefined color set

One is a predefined set of values. This is shown in the following table:


2. Hexadecimal Color Codes

Since the color drawn by Matplotlib is same as what we use in web development as well, we can use the same Hexademical color codes. So all the colors between #000000 to #FFFFFF becomes valid!

3. RGBA Color Codes

And the final type of color code it supports is the RGBA color code. Again, this is similar to what we see in our web development activity. Hence color codes like (0,1,0,1) become valid color codes again!

So now that we know the different color codes we can pass, let us modify our code to use them.

Now for the sake of simplicity, I will choose the first option. That is, use the values from Matplotlib’s predefined color set. So from the color set, we can see that there are 8 values to choose from. Since we have three lines to draw, let me pick these 3 colors – yellow, red & black.

So with our colors now selected, let us modify the code to add these values. Since we only need to modify three lines of code calling plot(), the final looks like this:

import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x], 'y')
plt.plot(x, [xi*2 for xi in x], 'r')
plt.plot(x, [xi*3 for xi in x], 'k')

Since the three colors are represented by ‘y’, ‘r’ & ‘k’, I just plugged in those values to our plot() function call. So just like that, we get the below output plot with changed line colors:

Matplotlib Plot with changed line colors
Matplotlib Plot with changed line colors

So, there you have it! Since Matplotlib provided us with such a simple solution, this was pretty straight forward. But not all features will be as easy as this one. But we will tackle each one of these problems as and when they appear. So with that I will conclude this article over here. But if you still have any doubts about this, do let me know in the comments below. Until next time, ciao! 🙂


Matplotlib Save Plot To File In PNG Or JPG Format

Matplotlib can save the plot to a file in PNG or JPG mage format. In this tutorial, we will learn how to get Matplotlib to save it’s output plot to such a file.

Why To Have Matplotlib Save Plot To File?

Matplotlib does a wonderful job in creating excellent plots and charts for us . However, the problem is it uses its own output window while displaying its results. While this is ok for us when learning things, it can’t be used in production. This is because in production we need these plots to be available in standard image formats. In other words, we want Matplotlib plot to be available as PNG or JPG file formats.

However, since this is such a basic requirement, Matplotlib already has a built-in function for this. So this function will enable us to use the Matplotlib plots even in production.

Understanding Matplotlib Savefig Function

The savefig function present in Matplotlib will help us in saving out output plot to an image file. This function has a very simple signature that looks like this:

savefig(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None,
        transparent=False, bbox_inches=None, pad_inches=0.1,
        frameon=None, metadata=None)

Woah that’s a mouthful you say? Well, the function signature might be looking daunting, but trust me, this is a very simple function to use. Let us go by the arguments passed to this function one by one:

fname - This is an argument with the path and filename to the output file
dpi - This is the resolution of the output file in dots per inch
quality - This argument will help us define the quality of the image we want. Lower quality will result in smaller size of the output file and vice versa. It varies between 1(worst) to 95(best)
optimize - Bool variable. If set to true library will try to optimize the image

So in the above description, we have explained only the important parameters. But for the rest, you should check its official documentation. So in simple terms, the only parameters that we really want to use is the first parameter. It is the name and path of the output file. Rest of the other parameters are all optional.

So with this much knowledge, we can now start using this function. For easier understanding, let us just use the code and plot from our previous article. Currently, the code from our previous article looked like this:

import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])
plt.legend(['Blue=1x', 'Orange=2x', 'Green=3x'])

plt.axis([0, 20, 0 , 40])
plt.xlabel('This is the X axis label')
plt.ylabel('This is the Y axis label')
plt.title('Dummy Plot')

And it’s resulting output plot looked like this:

Simple Matplotlib multiline plot with legends and labels

Up until now, we have been creating plots using Matplotlib that looked like above. However, so far we had not saved this plot to an image file. So In the next section we will learn how to instruct Matplotlib to save the plot to an image file.

Matplotlib Save Plot To File Example Code

As mentioned earlier, we can use Matplotlib to save the output plot to a file using its savefig() function. So in our code above, we simply need to call this function with appropriate arguments. However, to keep this example simple, we will not pass all the arguments. We will only pass the first argument that is the name and path of the resulting output file. But before that, we should also make one more little change to our current program.

Notice that in the current code, we use to display the output plot. However, since we now want to save the plot instead of displaying it, we will remove this call. And in place of this, we will call our savefig() function.

So, the final code will look something like this:

import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])
plt.legend(['Blue=1x', 'Orange=2x', 'Green=3x'])

plt.axis([0, 20, 0 , 40])
plt.xlabel('This is the X axis label')
plt.ylabel('This is the Y axis label')
plt.title('Dummy Plot')      <------ Disable this line of code

With that simple change of code, we can finally find the output plot saved into a file called Matplotlib_save_plot.png. Here is how the final output plot of Matplotlib saved in the file looks like:

Final resulting image for Matplotlib save plot to file
Matplotlib plot saved to a PNG file

So that is it for this tutorial. Hope it was easy enough for you to understand how to save output plot to a file. If you still have any more queries about it, do let us know in the comments below. Until next time, ciao! 🙂


Matplotlib Add Legend To An Existing Plot

In this tutorial, we will learn how to use Matplotlib to add legend to an existing plot. We can use Matplotlib to visualize data in different forms such as bar plots, charts, lines etc. However, none of these plots will be meaningful untill a legend is added to them. So, we need to first learn what a legend is. Why it is useful in a Matplotlib plot. And finally, we will learn how to write a simple Python program to achieve this.

What is a legend in Matplotlib plot?

A legend in a Matplotlib plot is a small infobox, whcih helps us in understanding what the plot is representing.

For example, let us take a look at an existing plot from our previous tutorial. It looks like this:

Matplotlib output chart with three lines in a 2D plot

We can see that it is a two dimensional plot. It’s axes labels also tells us what data is used to plot it. However, there is one thing that is still not clear. We are seeing three lines drawn in the plot above. But what does each of these lines represent? That is the question that a legend of a plot will answer.

Each of the above three lines for example could be representing the acceleration of a metro line. So the orange line in the plot could be representing an orange metro line train’s acceleration. Green line in the plot corresponds to a green metro line’s acceleration and so on.

So to represent this information on the plot, we need to make use of legends.

Now that we understand what a legend in a plot is, let us learn how to add one to the above plot.

How to add legend to an existing Matplotlib plot

So let us go back to the Python code from our previous tutorial. It looked like this:

import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])

plt.axis([0, 20, 0 , 40])
plt.xlabel('This is the X axis label')
plt.ylabel('This is the Y axis label')
plt.title('Dummy Plot')

So we had added axes labels and title for the plot in our previous tutorials. It is now time to add legends to the plot above. From the code, we can see that the three lines where generated by multiplying their x-axis values by 1, 2 & 3 respectively. In other words, we got the blue line by multiplying x-axis values with 1. Similarly, orange line by multiplying x-axis values with 2. And finally, green line by multiplying with 3.

So our Matplotlib plot should have a legend that shows Blue=1x, Orange=2x and Green=3x. Do you agree?

Now, to draw a legend in the output of a Matplotlib plot, we will make use of a special function called legend(). Go through theMatplotlib legend function’s documentation. We can see that we can add legend to a plot by simply passing legend’s texts as a list argument to this function. So with this in mind, if we add a line of code like this:

plt.legend(['Blue=1x', 'Orange=2x', 'Green=3x'])

then we should be getting our desired output.

So, our final code to add legend to Matplotlib plot will look something like this:

import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])
plt.legend(['Blue=1x', 'Orange=2x', 'Green=3x'])

plt.axis([0, 20, 0 , 40])
plt.xlabel('This is the X axis label')
plt.ylabel('This is the Y axis label')
plt.title('Dummy Plot')

Notice that we added our legend() function call right after plotting the three lines. The legend values in legend() is also passed in the same order as to how they are plotted. That is we are plotting the lines in the order blue, orange and green. So our legend function’s parameter also lists legends for blue, orange and green in that same order.

With this, our final output plot looks like this:

Matplotlib add legend to an existing plot
Matplotlib add legend to an existing plot


Using Matplotlib to add legend to an existing plot is not difficult. It is as simple as calling Matplotlib library’s legend() function. However, we have to ensure that we are passing the legend parameters in the correct order. So that is all for this tutorial. If you still have any questions about this, do let us know in the comment below. So until next time, ciao! 🙂


Add Title To Matplotlib Plot Using Python

In this tutorial, we will learn how to add title to a Matplotlib plot using Python. The Matplotlib library gives us a special function that we can use to achieve this. We are going to learn more about this function and how we can use it. But before that, let us first understand what a title is? Why do we need it?

What Is A Title?

A title is a short heading describing the gist of a content. But in our case, we can simply say that a title in Matplotlib plot will give us a hint of what the plot is all about.

How To Add Title To Matplotlib Plot?

So now that we understand what a title is, let us see how we can add it to our Matplotlib plot.

But before we begin, let us first take a look at our last tutorial. In that tutorial, we had just learned how to add labels to the axes of the plot. The output plot of that tutorial looked like this:

Output plot of previous tutorial containing axes labels
Output plot of previous tutorial containing axes labels

Although the above plot looks complete, it is still missing one important element. We are still not able to make out what this plot is all about!

This is because the plot is not having a title. If there was a title in that plot, it would have told us what it is all about.

So now that we know the missing element, let us learn how to add it.

But first, let us get the original code from our previous article that gave us the above plot. It looks like this:

import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])

plt.axis([0, 20, 0 , 40])
plt.xlabel('This is the X axis label')
plt.ylabel('This is the Y axis label')

So, with the above code, it is now time for us to learn about a new function of Matplotlib. This is the function that will help us add title to our plot. This function is part of the sub module pyplot of Matplotlib.

Introducing the Matplotlib title function

The function is simply called title(). The signature of this function looks like this:

matplotlib.pyplot.title(label, fontdict=None, loc='center', pad=None, **kwargs)

From the above function signature, we can see that it can accept a few arguments.

The first argument label will accept a string of text. So we can see that it is text that would get displayed as our title.

The second argument will accept the font information. So we can actually chose our font type here. We can also choose its size, style etc. Take a look at its documentation again to know more.

Next, the third parameter loc will help us in positioning our title. It can be set to one of the following positions: center, left or right. It’s default value is center.

Finally, we will take a look at it’s last parameter pad. It is used to add padding to the title text. So this padding is applied from the top of the axes.

With this much of information in our hand, we can now add our own title to the above plot. Since this plot is a dummy plot, let us use the title “Dummy Plot” for it. So with this, our code will now look like this:

import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x])
plt.plot(x, [xi*2 for xi in x])
plt.plot(x, [xi*3 for xi in x])

plt.axis([0, 20, 0 , 40])
plt.xlabel('This is the X axis label')
plt.ylabel('This is the Y axis label')
plt.title('Dummy Plot')

From the above code, you can see that we have passed only one argument. The title of the plot with text ‘Dummy Plot’. So we have left all other parameter values to remain at its default values. With this, our new Matplotlib output plot looks like this:

Final Matplotlib output plot with added title
Final Matplotlib output plot with added title

This concludes our current tutorial. If you still have any more doubts on this, do let us know in the comment below. We will be happy to help.

Until next time, ciao! 🙂