Categories

## How To Plot Pie Chart In Python Using Matplotlib

In this article, we will take a look at how we can plot a pie chart in Python using Matplotlib. But we wont stop there. Because we will also be looking at how to create labels & it’s explode feature.

## Plot Pie Chart In Python Using Matplotlib – The Basics

But before we do any of this, we first need to learn what a Pie Chart is. What is it used for. Because only after knowing this will be able to play with it. Does that make sense? Great! So then let us start from there!

### What Is A Pie Chart?

A Pie Chart is a circular representation of data. Where we will show each data in the data set as a sector in the pie chart. Wait! How are we going to show the value of that data then? Well it is simple. Each of the sector’s arc size will show the value of that data!

### Where Do We Use A Pie Chart?

Okay all that is well and good. But where do we use a Pie Chart? Well, a Pie Chart is very useful when we want to compare the sector size to the size of the Pie Chart. So in other words, it is useful when we want to compare a value against the total sum of all the values! Does that make sense?

## How To Plot A Pie Chart In Python

Okay. Now that we know what a Pie Chart is, let us see how we can plot one using Python. Once again, Matplotlib library comes to our rescue!

So we can use our Matplotlib library to plot a Pie chart in Python. But how do we do that? Well, take a look at the code below for that:

``````import matplotlib.pyplot as plt
x = [10, 25, 18]
plt.pie(x)
plt.show()``````

So as you can see from the above code, we have 3 numbers in our data set x. Their values are 10, 25 & 18. So now we want to use these values to plot a Pie chart. To do that, we just call the plt module’s pie( ) function and pass x to it. It is as simple as that! So when we call the plt module’s show( ) function we get the following Pie Chart:

So as you can see above, we have a basic Pie Chart with 3 sectors – Orange, Green & Blue. But did you notice something here? Their size is not the same, In fact their size corresponds to the value of our x dataset. Right?

So that is what I meant when I said “Each of the sector’s arc size will show the value of that data”. Aha! Now it all makes sense. Right?

But there is something not right in the above Pie chart. Can you see what it is? Yes, the Pie chart is not exactly circular. Right? How do we fix that?

### Plotting A Circular Pie Chart Using Python

Well, fixing it is actually quite simple. We just need to define our Plotting area to be a square and then it will correct itself! So if we modify the above code as follows:

``````import matplotlib.pyplot as plt
plt.figure(figsize=(4,4));
x = [10, 25, 18]
plt.pie(x)
plt.show()``````

It will get fixed!

Now it looks like a perfect circle. Great!

### How Is the Sector Size Of A Pie Chart In Python Calculated

So we can see three sectors in the above Pie Chart. But how is it’s width calculated to fit into the circle? Well it is actually quite simple. The pie( ) function in Matplotlib uses the formula:

``x/sum(X)``

to find the sector size. Here x is the data value this sector represents & sum(X) is the sum of all the values in the data set. So in other words, we are calculating the percentage of this value with respect to the whole data set. Hope that made sense to you!

But even though we now have a good circular Pie chart, there are a few things missing. One are the labels. Won’t it be great if we could label each of the sectors in the Pie chart? Second, how about it display the percentage of each sector as well?

That is what we will fix in the next section.

## How To Add Labels To Pie Chart In Python

So first, let us see how we can add labels to this Pie chart. Alright? So how do we do that. Well, it so happens that our Matplotlib library has a way to do that too! We just need to use the “labels” parameter when calling the plt.pie( ) function with appropriate labels. So how does the code then look like? Take a look at it yourself:

``````import matplotlib.pyplot as plt
plt.figure(figsize=(4,4));
x = [10, 25, 18]
labels = ['Bus', 'Car', 'Train']
plt.pie(x, labels=labels)
plt.show()``````

And the Pie chart created by this code looks like this:

So now we have our labels around the sectors of this Pie Chart. Perfect!

## How To Add Percentage Values To Pie Chart In Python

Adding percentage values to this Pie Chart is also quite simple. We just need to call the autopct parameter and it will fill in the values for us! So the code to do that looks like this:

``````import matplotlib.pyplot as plt
plt.figure(figsize=(4,4));
x = [10, 25, 18]
labels = ['Bus', 'Car', 'Train']
plt.pie(x, labels=labels, autopct='%1.1f%%')
plt.show()``````

Here the value ‘%1.1f%% is the format specifier that tells Matplotlib to print the percentages in x.x% format!

So here is how the plot with percentage now looks like:

Finally, we will take a look at the Explode feature of Matplotlib.

## Explode Feature Of Pie Chart Using Matplotlib

This feature will allow us to split the sector and move it slightly above it’s center. It is difficult to explain what I mean by this using words, so let me show you by directly using it:

``````import matplotlib.pyplot as plt
plt.figure(figsize=(4,4));
x = [10, 25, 18]
labels = ['Bus', 'Car', 'Train']
explode = [0.1, 0.3, 0.2]
plt.pie(x, labels=labels, explode=explode, autopct='%1.1f%%')
plt.show()``````

Here the “explode” values that we are passing tells the Pie chart to offset the sector by so much fraction from the center of the pie.

So here is how the final Pie Chart looks like:

So there you have it. That is how we can draw a Pie chart in Python using Matplotlib library. I hope I have covered all the things relevant to drawing these Pie charts. But if you have any doubts regarding these, do not hesitate to ask in the comments. I will be more than happy to help!

So until next time, take care! ðŸ™‚

Learn How To Plot Histograms Using Python

Categories

## How To Plot Bar Chart In Python Using Matplotlib

In this article, we will learn how to plot a Bar Chart in Python using Matplotlib library. In our earlier articles, we learnt how to plot a Histogram and line plots. So this is going to be a follow up on that. But this time with Bar Charts!

So are you ready to learn about it? Great! Then let us start right away!

## Plot Bar Chart In Python Using Matplotlib – The Basics

So to begin with, we will start with the basics. Alright? Because if we get our basics right, everything else will become very clear. I hope you agree with me! So here is the first basic thing to know about:

### What Is A Bar Chart?

A bar chart is a chart that uses rectangular bars whose length is equal to the value it represents. Now this bar can either be a vertical bar or a horizontal bar. Alright? So it can be used in either ways. But the main thing is that it’s width is the value that it represents!

So it is quite simple then. Right? But how are we going to plot a bar chart using Python? Any Guess? Yep, using our good old Matplotlib library!

So how does the code of a simple bar chart using Matplotlib look like? Let us take a look at it next!

## Example Plot Of A Bar Chart In Python Using Matplotlib

So here is our example code that shows us how we can do this:

``````import matplotlib.pyplot as plt
plt.bar([10, 12, 15], [18, 6, 24])
plt.show()``````

Okay. It looks pretty straight forward. So what is going on here?

As you can see in the first line, we are importing the standard plt module from the Matplotlib library. Now this module is like the Swiss army knife of the library. Because this is the module that has all the plotting functions.

So in this case, since we need to plot a bar chart, we will call the bar( ) function! Alright? So that is what we did in line 2.

``plt.bar([10, 12, 15], [18, 6, 24])``

But what are those two list values we are passing here? They are the X & Y co-ordinates. So the first list [10, 12, 15] gives the x-axis co-ordinate values. It is where the left margin of our bars will be drawn. On the other hand, the second list [18, 6, 24] gives us the height of the bars!

And finally in line3, we call the plt.show( ) function that will display our bar chart!

So how does our final Bar Chart look like? Well, take a look at it for yourself!

So there you go! That is how we plot a bar chart in Python using Matplotlib. It is quite easy to plot. Right? But if you still have any doubts, do let me know in the comments below. I will be more than happy to help! ðŸ™‚

Categories

## How To Plot Histogram In Python Using Matplotlib

So in this article, we will take a look at how we can plot histogram in Python using Matplotlib library. Now this is some thing quite different from the basics of line plotting we have seen so far. So I know you will need some time to get through it. So what I will do is to go through it in an easy to understand way. Alright?

So relax, take a cup of coffee if you want to. As we will now look into the plot of histogram in Python using Matplotlib!

## Plot Histogram In Python Using Matplotlib – The Basics

To get started, let us first learn a bit about what Histogram plot is. And then we will look at other questions. Like where it is used and how to draw it using Matplotlib. Okay? Great! So here we go!

### What is an Histogram?

A histogram is a way to display frequencies of some thing. So how does it look like? In simple words, it is drawn using bars.

Oh wait a second! So does that mean that it is a kind of bar graph? Yeah you are right. Kind of!

So what happens is, the data that you want to show in an histogram is grouped together. But it does not mean that they are grouped randomly. But instead, similar data items are grouped together. Alright? Does that make sense? So when you plot, you will be plotting these grouped data on the chart. Okay?

Now there is one other thing. In Matplotlib, we call these groups of data as bins.

### What are Histogram bins?

So a histogram bin is nothing but a group of similar data. That is all it is. So there is nothing really confusing about it!

Alright. So now that we know what a histogram bin in Matplotlib is, it is time for us to see an example of it. So how do we go about creating a plot of histogram in Python? Here is an example of it.

## Plot Histogram In Python Using Matplotlib – Example

So we all know that to start a plot of something, we need data. Right? So how do we get this data? Since histogram is used to plot a lot of data, we cannot create it by hand. So what do we do then? We will have to take help of a library. Of course!

And what better library than NumPy to get a set of random numbers. Right? So that is what we will do. We will use Numpy to generate a bunch of random numbers.

But how many random numbers shall we use? 10, 50 or 100? Naah! We can surely go more than that. Right? So how about using 1000 random numbers? ðŸ˜‰

So here is the piece of code we will use to generate 1000 random numbers using Numpy!

``````import numpy as np
y = np.random.randn(1000)``````

That is it! That is all the code we need to create 1000 random numbers using Numpy! So easy. Right?

So now that we have our data ready, let us see how we can plot it as a Histogram using Python’s Matplotlib.

So the code to plot a histogram using Matplotlib looks like this:

``````import matplotlib.pyplot as plt
import numpy as np

y = np.random.randn(1000)
plt.hist(y);
plt.show()``````

That’s it! We just import pyplot module and call it’s hist( ) function with our data. And the Matplotlib library does the rest. It will go ahead and plot a Histogram in Python for us!

This is very easy right? And that is the beauty of Matplotlib library. The modules and functions are so well written that you can create beautiful histogram plot in Python easily!

So then how does the final output plot of the Histogram look like? Well, you see it for yourself!

### Matplotlib Histogram Bins

Woah! What happened here? We gave it 1000 input data points right? What happened to all of it then? Well let me explain. Here is what Matplotlib has done.

It has taken our 1000 data input and grouped them together into 10 bins. And then it created the above histogram!

So why 10 bins? Why not 12 or 15 or any other number? Now that is a valid question for you to ask. So let me tell you why the number 10.

It is because that is the default number of bins Matplotlib will create for any number of input data you give to it. Okay? Does that make sense?

So in simple terms – Matplotlib took our 1000 data & grouped closer numbers together into 10 bins. It then went on to create the above histogram plot!

So that is all there is to it! But what if we want to have more than 10 bins? Well, we will come to that soon, but not now. Because it is going to need it’s own article that I will write next!

So see you in the next article!

Categories

## How To Use Different Line Color And Marker Color In Matplotlib

In this article, we will learn how to to set different line color and marker color in Matplotlib plot. But if have seen my earlier article, I showed you how we can set colors to markers. Right? So this will be a follow up on that article. Alright?

So what is the problem we are trying to solve here? Well you see, we want to have a plot with lines connecting markers. But then main thing is that we want different line color and the marker color in it! So how can we do that? Let me explain!

So first, let us take a look at our earlier plot. This is how it looked like, right?

So as you can see in the plot above, we had changed the color of the triangle markers to magenta color. Right? So what was the code we used to generate this plot? Let us take a look at it as well:

``````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], 'm^')
plt.show()``````

So we used the color code ‘m‘ in the third plot to get the color. Right? But what is missing here? Well, you can see that there are no lines drawn. Correct? So how do we go about fixing that? And more importantly, how can we add lines with different colors?

Well, to do that we will need to use certain keywords in the plot( ) function! That is the key to solving this problem! Does that make sense? Great!

So then what keyword do we need to use? Well you see, Matplotlib gives us a lot of keywords to use when plotting. So there are special keys for setting line color as well as marker color!

But how do these keywords look like? Let me explain.

## Keywords To Use For Different Line Color And Marker Color In Matplotlib

There are three keywords we can use to set the color of a line and the marker. They are:

color or c – So by using a color or c keyword in our plot( ) function, we can set the line color of a plot.

markeredgecolor – By using this keyword, we will tell Matplotlib what color to use to draw the edges of our marker.

markerfacecolor – By using this keyword, we can tell Matplotlib what color to use for the face of our marker.

These are the 3 keywords than we can use to set different line color and marker color in Matplotlib. So now that we know what to use, let us next see how we can use it. Alright?

What better way than to use our previous plot and to change it’s color? Right? So let us do just that!

Let us change the color of our plot line to be Yellow while the triangles to be Red with a green border. Alright? So how will our plot then look like? Any guess?

Well, take a look at it yourself below:

Woah! That is nice, right? We now have total control over the colors we can use in our plots, right? So what is the code change we did to get this? Take a look at the code for yourself!

``````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], color='yellow', marker='^', markeredgecolor='green', markerfacecolor='red')
plt.show()``````

So there is a tiny little change we have done to get this working. As said earlier, we simply used the keywords to set the color like we want. And it did work as we wanted. Right?

## Conclusion

So that is all there is to set different line color and marker color in Matplotlib. You just need to use the right keyword and it will work like a charm!

So with that, I will end this article now. But if you have any doubt about it, do let me know in the comment below. I will be more than happy to help!

So until next time, take care! ðŸ™‚

Categories

## How To Change Marker Color In Matplotlib

So in this article, we will learn how we can change the marker color in a Matplotlib plot. We will first see how we draw these markers and then see what we can do to change their colors.

Does that sound good? Great! Then let us start right away!

But before we start looking on how to change the Marker color of a plot, we need a plot. Right? But where do we get one?

Well, how about we make use of the plot we got from our previous article:

How To Change Marker Style In Matplotlib

That plot should be good enough. Right? So we will use just that!

Here is how the plot then looks like:

But what do we see here? We are seeing that each of the line marker in the plot already has different color. Right? But how did that happen? Who set the color for these markers?

Well the answer to that lies in the default behavior of the Matplotlib library. Because, even if we did not set those color, the library did it by itself. It made sure that each of the line markers got a different color.

That is cool! right? Because in that case, we will not have to worry about setting color ourselves. Isn’t it?

Well yes. That is true for most of the time. But there are times when we want to set the markers with a specific color. So having an option to change the marker color In Matplotlib is still needed. Right?

So then how can we do that? Well that is when the parameters of plot( ) function once again helps us! Here is how we can use it to change the marker color.

## Change Marker Color In Matplotlib

So before we look at how to change the marker color in Matplotlib, let us look at current code. The code that is responsible for the plot created above. This is how that code looks like:

``````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.show()``````

So using the above code we got three sets of markers in the above plot, right? And each set had a different color set to it. But what if I want the triangle in the first set to be in the color of magenta?

Well, luckily we can do that! How? By passing our desired color value to the plot( ) function. So the code for that will then 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], 'm^')
plt.show()``````

Notice the addition of the color value “m” to our third plt.plot( ) function call? That is what will do the trick for us! Here the alue “m” stands for the color “magenta”. This tells the plot( ) function to draw the triangles using magenta color!

So then how does our final plot look like then? Take a look at it for yourself!

So what do you see?!

As you can see, the color of the triangles have changed from green to magenta. And that is what we wanted. Right? ðŸ˜‰

But then you must be asking what are all the available colors that you can use? Right? Well, they are the same set of colors that you used while changing line color in Matplotlib earlier! So it is quite easy then. Isn’t it?

So there you have it! That is how you change the marker color In Matplotlib. With this, I will end this article now. But if you have any questions, do let me know in the comments below.

So until next time, take care!

Categories

## How To Change Marker Style In Matplotlib

So in the previous article, we say how to change line style in Matplotlib. But in this article, we will take a look at how we can change the marker style in Matplotlib. So let us start with some idea about what these markers are in the first place. Shall we?

## What Are Markers In Matplotlib Plots?

So for us to learn what markers are in Matplotlib plots, let us take a look at our previous example. Alright? Show this is the plot that we had in our previous example:

So as you can see here, we have 3 lines drawn using Matplotlib. Right? But how did we get these lines in the first place? Any guess?

To understand that, we need to take a look at the piece of code that generated this plot. So here is what that code looks like:

``````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.show()``````

So as you can see, the three lines we have plotted are drawn using these 3 lines of code:

``````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], ':')``````

And what is the data set used to plot these lines? There are 3 sets of data and they are:

``````[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30]``````

So as you can see, the three data sets shown above is what resulted in the 3 lines above.

But here is the thing. The lines that we have drawn in the plot are nothing but connections to these points. Right?

So in Matplotlib, we call these points as Markers and the lines joining them as Segments.

Aha! Now you know what these markers are, right? But there is another important thing you should notice here. The plot we have in the above pic is made up of both Markers & Segments. So the above Matplotlib plot has both Markers & Segments in it!

Woah..! We didn’t knew that the plot had markers in it right? But where is it then? Why can’t we see it?

Well it is because the markers in this plot are drawn using their default style and hence it is not clearly visible. Wait, what is the default style of a marker then?

### What Is The Default Style Of A Marker In Matplotlib Plot?

The default style of a Matplotlib Marker is to draw it as a point. And this is the reason why we are not able to see it. Because we are then connecting them by lines!

But then this begs us the next question:

### What can we do to make the markers in Matplotlib visible?

So how are we going to show clearly then? Well, the answer to that once again lies in the parameters we pass to the plot( ) function.

Wait, so how will that look like then?

Well, instead of using the plot( ) function to draw default markers and lines, we do something else. We will ask Matplotlib not to use default markers and also not to draw the lines!

So then, how will that code look like? Well, take a look at it yourself!

``````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.show()``````

So when we run this piece of code, what do you think will the plot look like? Any guess?

Woah! Where did this nice little plot come from?! How did we get those cool looking stars and triangles in the plot? Huh?!

### How To Change Marker Styles In Matplotlib

Well here the thing. When we used the marker style ‘*’, ‘+’ and ‘^’ symbol in our code, it got translated to that. Now that is one nice little feature that Matplotlib library is giving to us. Right?

So how do we know what all Marker styles are made available to us by Matplotlib then?

Well that is when this nifty table below will help you out! Take a look at it. It is showing you all the marker styles you can draw on your Python plot to make it look pretty!

And this is how you can get some nice little pretty plots using Matplotlib Python library. So I hope this was quite easy to understand for you. But if you still have any questions around it, do let me know. Because I will be more than happy to help! ðŸ™‚

Categories

## How To Change Line Style In Matplotlib

If you have been working with Matplotlib to plot lines, you might be looking for how you can style lines. Right? So if that is the case, they you have come to the right place. Because in this article, we will learn how to change line style in Matplotlib.

But before we do that, I hope you already know how to plot multiple lines on Matplotlib. But if you do not know, then take a look at the article linked above. That should get you going. Alright?

Okay then. With that, it is time for us to get started on changing the style of our lines now! Are you ready?

## Drawing Multiple Lines Using Matplotlib

So as I said in the earlier section, we first need to have the code to draw multiple lines. Here is that code we have from our earlier article:

``````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.show()``````

So this is the same piece of code we have taken from our earlier article. When we run this code, we get the following output:

So as you can see from the above pic, we have 3 different lines plotted on the same graph. But what is even more important is that all these lines are in different color. That is good. Right?

But what we want to do now is to change the line style in this Matplotlib output. Correct? So how do we go abut doing that?

## How To Change Line Style In Matplotlib?

With the basic multi line plot ready, let us now see how we can change the style of these lines.

So how do we go about doing this? Any guess? I want you to think a little bit to see if you can make a guess before you look for the answer. Alright? Just take a minute or two to think it over before you read further.

Okay. Here is what we can do to change the line style that we draw using Matplotlib:

Just like we could change the color of our lines ourselves, we can also change the style of these lines. So how did we change the color of our lines using Matplotlib to what we want, earlier? Yes, we passed in a new parameter to our plot( ) function. Right?

So in the same way, we can change the line style in Matplotlib as well. By passing our desired style as a parameter to our plot( ) function!

So how does that look like? Well, we just need to pass in the style we want as another plot( ) function parameter. So we modify our code in the plt.plot( ) function as shown below:

``````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 what happens when you do that? You have just changed the line style of the plots. So here is how it now looks like:

Now that looks like a perfect plot, isn’t it? But this begs us to ask the next question:

### What Are The Options Available To Change The Line Style In Matplotlib

So there are 4 line styles that Matplotlib provides us to choose from. They are:

So if you choose from any one of these styles, you can get some pretty looking plots out there!

## Conclusion

So that is all there is to changing the line style of a Matplotlib plot! You just have to add a new parameter to the plot( ) function with the style information. That is it and then it just works!

Pretty easy way to achieve what we want then, right? ðŸ˜‰ That is the beauty of Matplotlib library. It has so many interesting features with such a simple API!

So then what does our final code look like? Here it is:

``````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.show()``````

So with that, I will end this article now. But if you still have any questions, do let me know in the comment below. I will be more than happy to help! Alright?

So until next time, take care guys and gals out there! Have a great day! ðŸ™‚

Categories

## 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! ðŸ˜‰

## 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!

## Conclusion

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!

So until next time, have a nice day! ðŸ™‚

Categories

## 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:

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])
plt.show()``````

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 can 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:

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')
plt.show()``````

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:

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! ðŸ™‚

Categories

## 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,

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.grid()
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')
plt.show()``````

And it’s resulting output plot looked like this:

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 plt.show() 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.grid()
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')
#plt.show()      <------ Disable this line of code
plt.savefig('Matplotlib_save_plot.png')``````

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:

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! ðŸ™‚