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

Categories

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

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

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

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:

## Conclusion

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

Categories

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

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.grid()
plt.axis([0, 20, 0 , 40])
plt.xlabel('This is the X axis label')
plt.ylabel('This is the Y axis label')
plt.show()``````

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

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:

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

Categories

## Add Axis Labels In Matplotlib Plot Using Python

In this tutorial, we will learn how we can add axis labels to a Matplotlib graph plot. So to do this, we will use the same plot we had got from our previous article. As this plot already has lines drawn along x and y axis, we will now add labels to its axes.

Before we learn how to add axis labels in Matplotlib, let us first understand its benefits. Why do we need axes labels in our plot in the first place?

## Why Do We Want To Add Axis Labels In Matplotlib Plots?

When we draw our plots using Matplotlib, we are passing a set of data to it. So Matplotlib is using this data set as its input to draw the plot. Hence, the output plot that it is drawing is in relation to this input data. We can check this by looking at our Matplotlib graph from previous tutorial.

### Understanding our previous tutorial’s Matplotlib plot

We had got the above plot using this Python 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.grid()
plt.axis([0, 20, 0 , 40])
plt.show()``````

So let us now compare both the code and its output plot shown above. When we look at the plot, what we are seeing is that it has 3 lines drawn in a 2-Dimensional space. But this 2-Dimensional space will have two axis. Its x-axis and its y-axis. From the plot, we can see that it’s x-axis values are ranging between 0 and 20. But on the other hand, its y-axis values are between 0 and 40.

But what are these values? How did we get these values?

When we take a look at our code, we are seeing that x is a value ranging between 1 & 10. But on the other hand, our program is calclulating the y-axis values for each line.

For the first line, we get the y-axis values by multiplying the x-axis value by 1. But in the second line, we get our y-axis values by multiplying the x-axis value by 2. Similarly, we get the values of our third line by multiplying the x-axis value by 3.

Now, we know how we got the y-values. But we still don’t know what the x and y values represent. What are their measuring? What are its units?

Now if we gave this Matplotlib plot to someone else, even they will not know what x-axis and y-axis values are, isn’t it?

Therefore we need a way to describe these values in our plot. We need a way to mention what x-axis and y-axis values stands for. And we can do this by adding labels to our axes.

## Functions To Add Axis Labels In Matplotlib

Lucky for us, adding labels to axes in Matplotlib is very easy. The library has these two useful functions that does exactly this.

plt.xlabel() – This is a Matplotlib function we can use to add label to the x-axis of our plot. A label is simply a string of text. So we can pass this label as a parameter to this function and call it. And as a result of this, the Matplotlib’s output plot will now have the label written along it’s x-axis.

plt.ylabel() – Just like the previous function, this is a Matplotlib function we can use to add label to the y-axis of our plot. Here too, we will pass the label as a parameter to this function and call it. And as a result of this, the Matplotlib’s output plot will this time have the label written along it’s y-axis.

So if we simply call the above two functions with our label strings, we can get those labels added into our output plot.

So with this background, let us change the above code to add our labels to both x & y axis of our output plot. The code will thus 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.grid()
plt.axis([0, 20, 0 , 40])
plt.xlabel('This is the X axis label')
plt.ylabel('This is the Y axis label')
plt.show()``````

From the above code we can see that we have called our xlabel and ylabel functions with labels right after we have drawn our axes. The label we added to our x-axis reads:

This is the X axis label

and for our y-axis:

This is the Y axis label

So as a result of this code, our final Matplotlib plot output looks like this

So from the above plot, we can see that we have successfully added our labels to the plot.

## Conclusion

So that is it for this tutorial. We just saw that adding labels to our Matplotlib output plots are pretty straight forward. We just need to call its given function with appropriate labels and it should work. If you still have any questions, do comment below and I will try to help you out. So until next time, ciao! ðŸ™‚

Categories

## Matplotlib Change Axes Size In Python

While working on Matplotlib, we can change the axes size of its output plots. Matplotlib provides us with specific functions to modify individual axes values. So we can write Python programs to modify these axes size.

In our previous tutorial, we created a simple Matplotlib plot of multiple lines along with gridlines. However, in that plot we can see tht the size of each of the two axis where auto-determined. Since we used x & y values ranging between 1-10 & 0-30 respectively, axis size was also so to the same range.

However, we can actually change this. We can use Matplotlib to change axes size by making use of its appropriate features.

## Understanding How Matplotlib Changes Axes Size

So let us go back to our previous plot, which looked like this:

The code we used to generate the above chart 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.grid()
plt.show()``````

As mentioned earlier, we can see from the above code that x-axis values ranges between 1 & 10. On the other hand, values of y-axis is determined by the 3 lines we plotted on the graph. Their values where calculated by multiplying the values of x by 3 different values – 1, 2 & 3.

So by analyzing this, we can see that the highest y value achieved is from line number three. But line is being drawn using the code:

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

So, we can see that the highest value of y it can achieve is when we multiply the highest value of x with 3. But x ranges between 1 & 10. So the highest value that y can achieve is:

``````yi = xi*3 where xi=9 (because it is less than 10)
yi = 9 * 3
yi = 27``````

Hence, the highest value of y is 27. Our graph is also confirming this. We can see that the value of y axis of our 3rd line is not going beyond 27.

So with this knowledge, Matplotlib is drawing the x-axis of the plot to be up to 10. But on the other hand, it is stretching the y-axis to 30. It did this to accommodate the highest y-axis value of 27 of our 3rd plot.

## Programming Matplotlib To Change Axes Size

So now that we understand how Matplotlib calculates the axes values automatically, we will now learn how we can change this. In order for us to achieve this, we will use yet another function of Matplotlib.

### Matplotlib Axis Function

In order to control the size of our plot axes, Matplotlib provides us with another function called the axis function. The signature of this function looks like this:

``````matplotlib.pyplot.axis(*args, **kwargs)
where args = [xmin, xmax, ymin, ymax]``````

From the above signature, we can see that we can set the minimum and maximum values of x & y axis using xmin, xmax, ymin and ymax. You should also keep in mind that we need to pass these parameters as a Python list variable.

However this is not it. There is one another interesting feature of axis(). It is that if we simply call it without passing any parameters, it will return the current values of xmin, xmax, ymin ymax!

So axis() acts like both a GET function and a POST function.

One more thing to keep in mind while using axis() is that we need to call it before calling our plt.show().

Now enough of the theory behind this function. Let us understand it better by exploring it with our example plot.

## Code For Matplotlib Change Axes Size

So we will now modify our code to include axis() function call as follows:

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

When we run this program, what we get is the current size of the axes of our plot:

``````plt.axis()
(0.59999999999999998, 9.4000000000000004, -0.30000000000000004, 28.300000000000001)``````

So the above code returned us with the current size of our plot. Let us now modify this code further so that it can change the size of our plot axes values. To do this, let us modify our code 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.grid()
plt.axis([0, 20, 0 , 40])
plt.show()``````

By adding the parameters (0, 20, 0, 40) to our plot axis function, we have increased the size of both our axes. So the x-axis is extended to 20(xmax=20) while the y-axis is extended to 40 (ymax=40).

When we now run this program again, we will finally get this Matplotlib output plot:

From the above plot, we can clearly see that the x-axis is increased upto 20 while the y-axis of the plot is increased to 40. So this is how we can use the axis() provided by Matplotlib to change xxes size of our output graph plot.

I hope this tutorial was helpful to you. If you still have any questions about it, do let me know in the comments below. So until next time, ciao! ðŸ™‚

Categories

## How To Add Grid To A Matplotlib Plot Graph Using Python

In this tutorial, we will learn how to add grid to a Matplotlib plot graph using Python. If we look at our previous article, we had learnt how to draw multiple lines on a graph using Matplotlib.

However, if we take a look at the graph it had produced, we see that it’s background was mostly blank. But wouldn’t it be nice if we could get some sort of reference grid lines in there? This will help is interpreting the chart way better; is’nt it? Then let us see how we can achieve this.

## Finding The Function To Add Grid To A Matplotlib Plot Graph

The first thing that we need to do now is to see if Matplotlib library already provides a function to add grid to our plot. By checking through its documentation, we do come across it’s grid function. But what does it do?

### Grid function in Python Matplotlib – What does it do?

By looking into the Matplotlib’s documentation, we can see that the grid function has the following signature:

``grid(b=None, which='major', axis='both', **kwargs)``

From the above signature, we see that the grid function takes in 3 parameters. However, all these four parameters are optional. So we can simply call plt.grid() function and it should still work!

#### Understanding the grid function parameters

If we take a look at each of these parameters in the documentation, we see that they do simple operations:

• b – This is a boolean value which simply turns the grid lines ON or OFF
• which – This parameter indicates which grid lines to make changes on.
• axis – This parameter indicates which axis to make changes on.
• kwargs – This parameter will define the properties of the grid lines.

Hence, we can see here that we simply need to use this Matplotlib grid function to get our background grid lines working in our plot.

Based on this, we can then rewrite our program from our previous article as follows:

``````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 we can see that the code is pretty much the same for the first 5 lines. However before we call the show() to display our plot, we will add the grid lines. We do this by adding our grid() as follows:

``````plt.grid()
plt.show()``````

If you look at the above code, you will see that we are simply calling the grid() without any parameters. So we are letting the function just use its default values.

## Final Code To Add Grid To A Matplotlib Plot Graph

So here is the full code that you can use in your Python interpreter to get the plot with grid lines in the background of our figure:

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

With this code, we finally get the following image:

With this, we complete our tutorial here. Hope this explaination on how we can add grid to a Matplotlib plot graph using Python was clear. If you still have any doubts, do let me know in the comments below. So until next time, ciao!

Categories

## Matplotlib Plot Multiple Lines On Same Graph Using Python

In this tutorial, we will learn how to use Python library Matplotlib to plot multiple lines on the same graph. Matplotlib is the perfect library to draw multiple lines on the same graph as its very easy to use. Since Matplotlib provides us with all the required functions to plot multiples lines on same chart, it’s pretty straight forward.

In our earlier article, we saw how we could use Matplotlib to plot a simple line to connect between points. However in that article, we had used Matplotlib to plot only a single line on our chart. But the truth is, in real world applications we would often want to use Matplotlib to plot multiple lines on the same graph. This tutorial will explain how to achieve this.

But before we start, let us first create the dataset required for our tutorial.

## Creating dataset for Matplotlib to plot multiple lines on same graph

Just like we did in our previous tutorial, we will simply generate our sample dataset using Python’s range function.

Now, if you are unfamiliar with Python’s built-in range function, take a look at this tutorial we wrote about it earlier.

So the code to generate multiple datasets with Python’s range function looks like this:

``````import matplotlib.pyplot as plt
x = range(1, 10)``````

With this, we now have our sample dataset saved in the Python variable x. So its time to start using these values to plot our chart.

## Using Matplotlib to plot multiple lines on same graph

Wait a second! Using above code we got only one set of data. How are we going to use it to plot multiple lines on the same graph?

Well, the answer is that we can convert this single dataset into 3 different datasets by simply multiplying it with different values. So for example to create three different datasets we can do something like:

``````Pseudocode:
===========
Dataset1 = 1 * x
Dataset2 = 2 * x
Dataset3 = 3 * x``````

Cheeky huh?! ðŸ˜‰

So with our required datasets in place, we can start writing our code to draw different lines out of it. Here we go!

``````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 these three lines of code is all that is required to draw 3 different lines on our graph using Matplotlib. But are you not so sure what these three lines are doing? Then let me explain the first line of code first. This should make the rest of the code clear as well, right?

Let us take a look at the first line of code again:

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

What we are doing over here is that we are calling Maplotlib’s plot function. The only job of this plot function is to draw or plot our data on the Matplotlib’s canvas!

But if you are not familiar with Matplotlib’s canvas, you should first read this article on Introduction to Matplotlib.

### Understanding Matplotlib plot function’s parameters

From this first line of code, you can also notice that we are passing two parameters to our plot function. The first parameter we pass is simply the value of x. This forms the x-axis values for our plot. On the other hand, the second parameter forms the y-axis values of our plot. But what is exactly happening here? Why is the second parameter looking so complicated?

``[xi*1 for xi in x]``

What we are doing over here is that we are looping over each value of x and multiplying it by 1. So this is the final value that we use for the y-axis of the plot.

Now if you are able to keep up with me so far, then you will know what the last two lines of code does as well, right? You can see that they also do the same thing as our first line of code. The only difference is that they multiply the y-axis values with different co-efficients.

## Display the final output graph

So far we in the code generated our sample dataset and drawn three lines using it on the same graph. But if you have followed along with me and typed in the code, you realize that no image is yet displayed. But why so? The reason is that we might have drawn the image on Matplotlib canvas, but we haven’t displayed it yet. In order to display our final output image, we still need to call one another function:

``plt.show()``

This Matplotlib’s show function is the one that is responsible to display the output on our screen. This function does not take any parameters as seen. But calling this in your code is a must if you want to display the graph on screen.

So with just these 6 lines of code, we have been able to make Matplotlib plot multiple lines on same graph.

Here is the final output image drawn using the above piece of code.

One another interesting thing for us to note here is that Matplotlib has plot these multiple lines on the same graph using different colors. This is a built-in feature found in Matplotlib. If it needs to plot more than one line on the same graph, it automatically chooses different colors for different lines! In this way, we will be able to differentiate different datasets represented on a single chart. Isn’t it cool & beautiful? ðŸ˜‰

## Conclusion

So this is how we can make Matplotlib plot multiple lines on the same graph. By using Python’s Matplotlib and writing just 6 lines of code, we can get this result.

Here is the final summary of all the pieces of code put together in a single file:

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

Matplotlib is an easy to use Python visualization library that can be used to plot our datasets. We can use many different types of datasets and Matplotlib will still be to handle them. By familiarizing ourselves with this wonderful Python library package, we are adding new tool into our arsenal.

Hope this tutorial was easy enough for you to understand. If you have any queries on Matplotlib or Python in general, do not forget to comment below. I will try my best to provide you with all the helpful answers I can give. With this, I will conclude this tutorial on Matplotlib. Until next time, ciao!