Categories
DATA MINING DATA SCIENCE DATA VISUALIZATION MACHINE LEARNING PROGRAMMING PYTHON TUTORIALS

Matplotlib Annotate Text In A Plot Using Python

In this article, we will learn how to annotate text in Matplotlib plot using Python. But if we only add annotation text to a plot, it will not look that great. Because we want that annotation to point to a particular location in the plot. Right? So we will also be looking at how we can add arrows to go with these annotations. By using arrows, we will be able to point it to a location on the plot as well.

Now does that sound good for you? Great! So then let u begin!

First thing first. Let us learn what an annotation is. Alright? Because knowing what an annotation does to a plot will help us know how to use it. Right? So let us start fro there.

What Is Annotation?

Annotation is a piece of text that we can add to a plot to add give some explanation. So that is all there is to it.

But then you may ask why we want to text annotate a Matplotlib? After all, we already have a way to add text inside a plot in Matplotlib. Right? We have already seen how we can do that in our earlier article. So then why do we need annotation as well?

Well, there is a simple reason for that. So you see, using text( ) function provided by Matplotlib is fine for simple texts. But for larger texts, we want to go for annotations because we can use arrows here! So that way we can use larger texts but still point this text a point on the plot using arrows!

So that is the real benefit of using annotated text in Matplotlib plots rather than normal text( ) function. I hope this is clear to you by now!

So with that, let us see how we can text annotate a point in the Matplotlib plot.

How To Use Matplotlib To Annotate Text In A Plot

So how do we add annotation to a Matplotlib plot? Well using the annotate( ) function from the pyplot module, of course!

So the pyplot module provides us with an annotate( ) function as well! So using this, we can add annotations to our plot. But how does the signature of this function look like? Let us take a look at it:

annotate(text, xy, xytext, arrowprops)

So this is the basic signature of the annotate( ) function. But this signature is not all of it. It is missing few more arguments. But they are all optional. So we have skipped what is not required.

So what do these arguments mean? To understand, let us take a look at them one by one:

text - This is the annotation text
xy - This is the x & y co-ordinates of the point on our plot to which we will be adding the annotation
xytext - This is the x & y co-ordinates where we want our annotated text to appear
arrowprops - This will define the properties of our arrow

I know this is all looking overwhelming. But it will become clear to you once we looked at an example code using that. Alright? So let us look at that right now!

Matplotlib Annotate Text Example

So here is our example code:

import matplotlib.pyplot as plt
y = [8, 10, 11, 12, 10, 9, 10, 8, 7, 11, 10, 9]
plt.plot(y)
plt.annotate('this is the point I want to point!',
xy=(4, 10), xytext=(5, 10.75), arrowprops=dict(facecolor='red'))
plt.show()

As you can see, we are using a simple data set y with 12 values in it. We are then calling the normal plot( ) function to plot this data. But the real meat is in our 4th line where we are using our annotate( ) function.

So as you can see, we are passing a number of parameters here. The first is the text parameter which simply reads “this is the point I want to point!”.

The next is the xy parameter which is the point we want to annotate. This is followed by the xytext parameter which allows us to set the location where we wan our text to appear.

And finally we have the arrowprops parameter which allows us to set the arrow properties.

So using this code we get the following plot:

Matplotlib Plot With Annotate Text
Matplotlib Plot With Annotate Text

So there you have it. This is how you can use Python Matplotlib library to create a plot with annotated text. I hope it was easy enough for you. But if you have any questions, do let me know in the comments below and I will be happy to help.

So with that, I will end this tutorial now. Hope you have a nice day! 🙂

Categories
DATA MINING DATA SCIENCE DATA VISUALIZATION PROGRAMMING PYTHON TUTORIALS

How To Plot Scatter Plot In Python Using Matplotlib

In this article, we will learn how to plot a Scatter plot in Python using Matplotlib. But before we do that, we will learn what a Scatter plot is and what all options are there for us to use. Sounds good? Great! Then let us start!

What Is A Scatter Plot?

A scatter plot is a type of plot that we can use to display values from two sets of data. So what happens is, we will take two sets of data of same length & pair them together. We then use this pair to plot the scatter plot. It is very important for you to remember here that both the data sets have to be of the same length!

But there is another thing to note here. It is that the scatter plot will have only points drawn and no lines in them. So in other words the points in the plot will not be connected together. But just the points scattered across the chart. Hence the name scatter plot!

What Is The Use Of A Scatter Plot?

We can use Scatter plot to see any correlation between two data sets. So what happens is, similar points get grouped together in the scatter plot. Now this can be a very valuable insight for us. Especially when looking at non linear relationships between the two datasets! Does that make sense?

So we can use a scatter plot to find any relationship between data points.

So now that we know the uses of a scatter plot, let us see how to plot it. But to do so, we need two sets of data. Right? So what do we do for that? Where can we find it?

How To Plot A Scatter Plot In Python

Here is what we will do. We will use our good old random function randn( ) from the Numpy library for that. Alright? So check this code:

import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(100)
y = np.random.randn(100)
plt.scatter(x, y);
plt.show()

So this is the code that will generate us a scatter plot using two sets of random data. But what is going on here? Let us go through the code line by line:

So in line 1 and 2, we are importing our Matplotlib and Numpy libraries.

But what is going on in line 3 & 4? Well, as I said earlier, we need two sets of data for our scatter plot. So we are using Numpy’s randn( ) to generate these data sets. We will assign them to variables x & y.

Next in line 5, we call our good old plt module’s scatter( ) function and passing x & y to it. So this is the function that will generate our scatter plot using x & y data!

Finally we call the usual plt.show( ) function to display our resulting scatter plot. So here is how it looks like:

A basic Scatter Plot With 100 variables
A basic Scatter Plot With 100 variables

So as you can see, there are 100 points taken from x & y variables to be plotted along the X & Y axis. So if there are any points that are similar, they will converge together here!

How To Change The Size Of A Marker

The above chart is all well and good, but is there a way to control the size, color & marker type in it? Well, lucky for us Matplotlib does give us an option for this. So to do so, we need to set the s, c & marker parameters in our plt.scatter( ) function!

So here is a simple example code that changes the size and color of our plot markers:

import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(100)
y = np.random.randn(100)
size = 20*np.random.randn(100)
colors = np.random.rand(100)
marker = "^"
plt.scatter(x, y, s=size, c=colors, marker=marker);
plt.show()

And here is how our final scatter plot would look like:

Scatter Plot with changed color, size & marker type
Scatter Plot with changed color, size & marker type

So there you have it! This is how we plot a Scatter Plot in Python. I hope this was easy enough for you to follow. But if you have any doubts, do let me know in the comments below. I will be more than happy to help!

Alright? So then see you until next time. take care! 🙂

What to learn how to plot a Pie chart using Matplotlib? Take a look at this!

Categories
DATA MINING DATA SCIENCE DATA VISUALIZATION PROGRAMMING PYTHON TUTORIALS

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:

Basic Pie Chart Using Python
Basic Pie Chart Using Python

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!

Fixed To Be A Circle
Fixed To Be A Circle

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:

Pie Chart With Labels Plotted Using Python
Pie Chart With Labels Plotted Using Python

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:

Pie Chart With Percentage Plotted
Pie Chart With Percentage Plotted

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:

Exploded Pie Chart
Exploded Pie Chart

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
DATA MINING DATA SCIENCE DATA VISUALIZATION MACHINE LEARNING PROGRAMMING PYTHON TUTORIALS

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?

Matplotlib plot with colored markers
Matplotlib plot with colored markers

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:

Different Line Color And Marker Color Plot image
Different Line Color And Marker Color Plot image

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
DATA MINING DATA SCIENCE DATA VISUALIZATION MACHINE LEARNING PROGRAMMING PYTHON TUTORIALS

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:

Change Marker Style In Matplotlib
Matplotlib plot with different marker styles

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!

Change Marker Color In Matplotlib
Change Marker Color In Matplotlib

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
DATA MINING DATA SCIENCE DATA VISUALIZATION MACHINE LEARNING PROGRAMMING PYTHON TUTORIALS

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:

An example Matplotlib plot with 3 lines drawn from 3 sets of data
An example Matplotlib plot with 3 lines drawn from 3 sets of data

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?

Change Marker Style In Matplotlib
Change Marker Style In Matplotlib

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!

Marker SymbolMarker Style
^Triangle Up
vTria. Down
<Triangle Left
>Tria. Right
1Tripod Down
2Tripod Up
3Tripod Left
4Tripod Right
pPentagon
sSquare
hHexagon
HRoated Hexagon
*Star
+Plus
Horizontal
DDiamond
dLean diamond
|Vertical Line
Available Marker Styles To Draw Using Matplotlib

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
DATA MINING DATA SCIENCE DATA VISUALIZATION MACHINE LEARNING PROGRAMMING PYTHON TUTORIALS

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:

Matplotlib multiple lines same graph
Drawing Multiple Lines Using Matplotlib

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:

Change Line Style In Matplotlib by passing in the style as a parameter to the plot() function.
Change Line Style In Matplotlib by passing in the style as a parameter to the plot() function.

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:

Style SymbolStyle Type
Solid Line
Dashed Line
-.Dash Dot Line
:Dotted Line
4 line styles available for us to choose from in Matplotlib

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