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!

Categories

## Using Matplotlib To Draw Line Between Points

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

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

## Creating dataset for Matplotlib to draw line between points

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

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

``import matplotlib.pyplot as plt``

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

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

``x = range(5)``

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

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

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

## Using Matplotlib to draw line between points

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

The general syntax of our plot function looks like this:

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

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

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

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

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

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

``plt.show()``

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

## Conclusion

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

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

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

Categories

## Difference between range vs arange in Python

In this article, we will take a look at range vs arange in Python. Learning the difference between these functions will help us understand when to either of them in our programs. Both range and arange functions of Python have their own set of advantages and disadvantages. This article will help us learn about them in detail.

To better understand the difference between range vs arange functions in Python, let us first understand what each of these functions’ do.

## range vs arange in Python: Understanding range function

The range function in Python is a function that lets us generate a sequence of integer values lying between a certain range. The function also lets us generate these values with specific step value as well . It is represented by the equation:

``range([start], stop[, step])``

So, in the above representation of the range function, we get a sequence of numbers lying between optional start & stop values. Next, each of these values are also getting incremented by the optional step values.

### range function example 1

So that was the theory behind the range function. Now, let understand it better by practicing using it. Fire up your Python IDLE interpreter and enter this code:

``l = range(1, 10, 2)``

When you hit enter on your keyboard, you don’t see anything right? That is because the resulting sequence of values are stored in the list variable “l”.

To be able to see the values stored in it, let us print individual list values. So, by indexing each of the list items, we get the following values printed out.

``````>>> l[0]
1
>>> l[1]
3
>>> l[2]
5
>>> l[3]
7
>>> l[4]
9``````

So we see a list of numbers, cool! But when you observe closely, you will realize that this function has generated the numbers in a particular pattern. You can see that the first number it has generated is after taking into consideration our optional start parameter. We had set its value to 1. Next, it is also honoring the stop value by printing the value 9, which is within our defined stop value of 10. If you try to index the list for any further value beyond this point will only return an error:

``````>>> l[5]
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
l[5]
IndexError: range object index out of range``````

So, this confirms that the last value we get will always be less than the stop value.

But the most important thing to observation we need to make here is the step size between each of these values. We can see that each of these values are incremented exactly with a step size of 2. This is the same step size we had defined in our call to range function (the last parameter)!

### range function example 2

Does this mean everytime we want to call range function, we need to define these 3 parameters? Not really. If we take a look at the signature of the arange function again:

``range([start], stop[, step])``

The parameters start and step (mentioned within the square brackets) are optional. This means that we can call the range function without these values as well like this:

``````nl = range(4)
>>> nl
range(0, 4)
>>> nl[0]
0
>>> nl[1]
1
>>> nl[2]
2
>>> nl[3]
3
>>> nl[4]``````

In this case, we have only the stop value of 4. As a result we get our sequence of integers starting with a default value of 0. The step value is also defaulted to a value of 1. So we get the integers in the range between 0 to 3, with a step value of 1.

Alright then, hope everything is clear to you up to this point. If this is the case with Python’s range function, what does the arange function in Python do?

## range vs arange in Python: Understanding arange function

Unlike range function, arange function in Python is not a built in function. But instead, it is a function we can find in the Numpy module. So, in order for you to use the arange function, you will need to install Numpy package first!

The signature of the Python Numpy’s arange function is as shown below:

``numpy.arange([start, ]stop, [step, ]dtype=None)``

Wait a second! Doesn’t this signature look exactly like our range function? Yes, you are right! Python’s arange function is exactly like a range function. It also has an optional start and step parameters and the stop parameter.

But then what is the difference between the two then?

## range vs arange in Python – What is the difference?

Where the arange function differs from Python’s range function is in the type of values it can generate.

The built in range function can generate only integer values that can be accessed as list elements. But on the other hand, arange function can generate values that are stored in Numpy arrays. We can observer this in the following code:

``````import numpy as np
a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> a[0]
0``````

We are clearly seeing here that the resulting values are stored in a Numpy array. Each of the individual values can hence also be accessed by simply indexing the array!

This begs us the next question. When should we use Python’s built-in range function vs Numpy’s arange function? To understand this, lets list out the advantages and disadvantages of each of these functions:

### Advantages of range function in Python

• range function returns a list of integers in Python 2. In case of Python 3, it returns a special “range object” just like a generator.

### Disadvantages of range function in Python

• range function is considerably slower
• It also occupies more memory space when handling large sized data objects.

### Advantages of arange function in Python

• Numpy’s arange function returns a Numpy array
• Its performance is wat better than the built-in range function
• When dealing with large datasets, arange function needs much lesser memory than the built-in range function.

So this is the fundamental difference between range vs arange in Python. We can understand them even better by using them more in our everyday programming.

I hope this gave you some amount of clarity on the subject. If you still have any more doubts, do let me know about it in the comments below. I will be more than happy to help you out.

Having said that, take a look at this article. It gives you a simple explanation on the “Difference between expressions and statements in Python“. I have spent considerable amount of time trying to understand these topics. Since there are not many articles available that explains them clearly, I started this blog to capture these topics. Hope you found them useful! If yes, do share them with your friends so that it can help them as well.

With this, I will conclude this article right here. See you again in my next article, until then, ciao!