Categories

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

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

## Matplotlib Add Text Inside A Plot Using Python

In this article, we will learn how to add text inside a plot using Matplotlib. But not just that. We will also look at how we can position this text inside the plot.

In our earlier articles, we had already seen how we can add titles and axis labels to our plot. Right? So this article will be a follow up of that. But only that we will be adding text inside the plot itself. This is unlike others where we added labels and titles outside the plot.

So how do we go about doing this? How can we add text inside a plot? If we can, can it be positioned wherever we want within the plot? These are some of the questions we will be answering next!

## How To Add Text Inside A Matplotlib Plot Using Python

So to answer this, let us draw a simple plot using the following code:

``````import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 20, 1)
y = np.arange(0, 2, 0.1)
plt.plot(x, y)
plt.show()``````

So this will give us a simple plot with a linear line that looks like this:

Okay. This is great! But now how do we go about adding a piece of text inside this plot? Let me say I want a piece of text that reads “This is cool!” written above the blue line, but somewhere in the middle? Can I do that in Matplotlib?

## The text( ) function

Of course you can! Matplotlib provides you with a very specific function for you to do just that! The function is called the text( ) function and it is part of the plt module of Matplotlib.

So what does the signature of this text( ) function look like? Here it is:

``plt.text(x, y, text)``

In the above text( ) function signature,w e see that it takes in 3 parameters – x, y, & text. But what do they do? Well, the parameters x & y gives the co-ordinates where the text is to be written. While the “text” parameter specifies the text we want to write!

So how does this all workout for us where we want to say “This is cool!” above the blue line? Well, first we need to set the x & y co-ordinates.

From the plot above, we can choose a value that is above the line and somewhere in the middle. Right? So what would be that value? Well how about it being 5 along the x-axis and 1 along the y-axis? In which case, we can call the text( ) function as follows:

``plt.text(5, 1, 'This is cool!')``

We will call this function just before plotting. So our final code will then become:

``````import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 20, 1)
y = np.arange(0, 2, 0.1)
plt.text(5, 1, 'This is cool!')
plt.plot(x, y)
plt.show()``````

So how will the plot look like for this code? Take a look at it for yourself!

Now that is what we wanted right?!

So there you have it. This is how we can add text inside a plot in Matplotlib using Python. Hope it was pretty easy to follow. But if you have any questions, do let me know in the comments below. I will be more than happy to help!

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

Categories

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

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:

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

## How To Plot Pie Chart In Python Using Matplotlib

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

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

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

### What Is A Pie Chart?

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

### Where Do We Use A Pie Chart?

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

## How To Plot A Pie Chart In Python

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

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

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

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

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

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

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

### Plotting A Circular Pie Chart Using Python

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

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

It will get fixed!

Now it looks like a perfect circle. Great!

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

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

``x/sum(X)``

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

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

That is what we will fix in the next section.

## How To Add Labels To Pie Chart In Python

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

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

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

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

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

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

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

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

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

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

## Explode Feature Of Pie Chart Using Matplotlib

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

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

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

So here is how the final Pie Chart looks like:

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

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

Learn How To Plot Histograms Using Python

Categories

## How To Plot Bar Chart In Python Using Matplotlib

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

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

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

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

### What Is A Bar Chart?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Categories

So in this article, we will look at a piece of hardware called the shift register and their modes of operation. But we wont stop there. Because we will also look at their use case, advantages & disadvantages.

So if you are new to computer hardware or learning about what goes inside a microprocessor, then brace yourself. As this is going to be an eye opener for you on how computer works!

So are you ready? Great! Then let us go!

To start with, let us ask ourselves the basic question – What is a shift register? Because only when we know what it is, does it make sense to learn about shift register modes of operation. Right? Let us answer that first!

## What Is A Shift Register?

A shift register is a piece of circuit that you will find inside a microprocessor. It is used to store and modify data. Now this is one of the simplest explanation I can give for a 2nd grade student.

But if you are some one who is studying about computers, this is just not sufficient. So I will have to explain it in a bit more detail. Alright? I will be getting a bit technical here. But it is how you will get a solid understanding of shift register. So you will have to bare it. Okay?

### Technical Explanation

Technically, a shift register is made up of a bunch of Flip Flops. So as you know, a flip flop is a circuit that can store information. It can store data that is in one of the two states – 0 or 1. Right? So what happens when you connect a bunch of these flip flops together? You get a “register“.

So a register is a circuit made up of a bunch of flip flops that can store data having values in 0s or 1s. Now, if that is the definition of a register, then what is a shift register?

A shift register is a type of register where data is shifted from one flip flop to another within the register. But this shift of data does not happen by itself. Instead, it needs a clock signal to do so. So for every input clock cycle, the data get shifted from one flip flop to another. Hence the name “Shift Registers”. Aha! That name now makes so much sense. Right?

The above pic shows how it works. So as you can see here, for every clock cycle, a new input bit enters Bit0. But at the same time, existing Bit0 value shifts to Bit1, Bit1 to Bit2 and so on. But what happens to current value of Bit7? The register will just throw it out! Removed forever!

Now there is one thing for you to notice in the above pic. It is that the bit value here is shifting left. Right? Because of this, we call it a “Left Shift Register“.

But does that mean we also have a “Right Shift Register”? You bet! We do have a right shift register where input is fed to Bit7 & Bit0 will thrown out for every clock cycle!

## Where Do We Use A Shift Register?

So now that we know how a Shift register works, let us see where we can use it.

### Using Shift Register For Multiplication

When you shift bits in a byte to the left, the value of the byte is multiplied by 2! So we can use a left shift register whenever we want to multiply a byte by 2.

### Using Shift Register For Division

When you shift a byte to the right, you are dividing it’s value by 2. So we can use a right shift register whenever we want to divide a byte by 2!

So with that, let us now look at the different modes of operation of a shift register.

## Shift Register Modes Of Operation

A shift register will work in one these four modes:

• Serial In Serial Out (SISO) Mode
• Serial In Parallel Out (SIPO) Mode
• Parallel In Serial Out (PISO) Mode
• Parallel In Parallel Out (PIPO) Mode

So let us take a look at each of these modes one by one. Alright? Here we go!

### Serial In Serial Out (SISO) Mode

In this mode of operation, the data is fed into the shift register serially for every clock cycle. That is, for every clock cycle, the data is shifted either to the right or left serially. The output is also taken out one bit at a time. So both inputs and outputs are serial here. Hence the name SISO. So then how does the Flip Flop connection look like? Take a look at it below:

### Serial In Parallel Out (SIPO) Mode

When we use the shift register in SIPO mode, we feed the input data serially but take the output data out in parallel. But again, this happens at every clock cycle. So how does that look like? Take a look at it yourself!

So as you can see here, we are still feeding the input data serially. But the output is no more serial. We are taking all the output bits at the same time, in parallel. So what this means is that we will get full 4 bit output every clock cycle!

### Parallel In Serial Out (PISO) Mode

In the case of shift register in PISO mode, we feed the input data in parallel but take the output data serially. So what this means is that we will be feeding multiple data bits as inputs for every clock cycle. But will be taking only one output bit for each clock cycle.

So then what will happen to the output of each flip flop? Well, even that will be fed as an input! So, we will be feeding two inputs after multiplexing them together. So how does that connection look like? Take a look at it below:

### Parallel In Parallel Out (PIPO) Mode

And finally, we have the shift register working in PISO mode. So can you guess what in this mode? Yes. In this mode of operation, you have both input and output data running in parallel. So how does that work? Take a look at it first!

So as you can see above, there is a major change in the way we connect the flip flops. In that, you do not see them connected to each other at all. So each input bit goes to a flip flop and it’s output is directly taken out. The only connection that is common to all these flip flops are the clock and clear signal!

So there you have it. Those are the different modes in which we can design a shift register to work. In the next section let us take a look at different types of shift registers that we can use.

## Types Of Shift Registers

Based on the way the data is shifted, we have 5 different types of shift registers. They are:

• Left Shift Registers
• Right Shift Registers
• Bidirectional Shift Registers
• Circular Shift Registers &
• Linear Feedback Shift Registers

Now let explain what each of these registers work like:

### Left Shift Registers

We have already talked about the left shift register. So I think you are familiar with it by now. If not, let me re-iterate. So in the case of a left shift register, the data is shifted to the left on each clock cycle.

### Right Shift Registers

This is just like the left shift register. But here it is shifting the data to the right on each clock cycle.

### Bidirectional Shift Registers

In the case of a bidirectional shift register, we can shift the data in both the directions. So you can shift the data either to it’s left or right!

### Circular Shift Registers

In the case of a circular shift register, the last output is connected back as input. So your data will not be thrown out. Instead, will be shifted either left or right in a circular fashion!

### Linear Feedback Shift Registers

In this type of shift register, the input of one flip flop will be linear output value of the previous flip flop.

It is now time to talk about the advantages & disadvantages of using a shift register. So what are they?

### Advantages Of A Shift Register

• They are very fast to use.
• Very quick when you want to convert data from serial to parallel or vice versa. They are faster than normal serial to parallel converter circuits.
• They are very simple in design. So you can easily rig up a circuit to create a shift register.
• We can use them to encrypt or decrypt the data.
• We can use them to a delay signal.
• It is used in CDMA to generate Pseudo Noise Sequence Number.
• We can use them to track our data!

### Disadvantages Of A Shift Register

While we could see that it has major advantages, shift register has one major disadvantage. That is:

• The strength of the output current coming from a shift register is not so strong!

So there you have it. Those where some of the advantages & disadvantages of using a shift register.

And with that, I will end this article now. But if you have any doubts, do let me know. Because I will be more than happy to answer them! Alright? So see you and take care until next time! ðŸ™‚

Categories

## What Are Hexadecimal Numbers & Why Do We Use It?

So in this article, we will take a look at what Hexadecimal numbers are. But we wont stop just there. We will also learn why we need to use them. We will take a look at few examples of hexadecimal numbers to know it better.

So does that sound like something you want to know more about? Great! Then strap yourself to your seat and read along. Because you are in for a treat with a world of numbers!

So first thing first, let us answer the basic question we have.

So to answer this, we first need to ask ourselves what a decimal number is. Alright? Because the numbers we use in our daily lives are based on decimal number system. So looking at hexadecimal numbers after analyzing decimal number will be so much easier. Right?

Alright then.

### Decimal numbers

They are the number system that has the digits 0 to 9. Right? But what do we do when we want to go beyond the number 9?

We use 2 digits to represent the next number. And these digits will now start with a 1 followed by another digit between 0 to 9.

So the next set of numbers will be 10, 11, 12, 13, 14 …… Correct? But what happens when we reach the number 19? We again start with our next number 2 and repeat the process again.

So it will now be 20, 21, 22, 23 ….

So what we see here is that we can only use digits between 0 to 9. But they can be grouped together in to multiple digits to count any number we want. Right?

Alright. I can now hear you asking me what does this have to do with Hexadecimal number?

Well this concept is very much related to hexadecimal numbers as well. How, you ask? Let me explain!

So just like we have digits between 0 to 9 for decimal, we use digits between 0 to F in hexadecimal system!

What? So how does the digits look like? They look like below:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E & F

These are the digits we use in a hexadecimal number system!

So as you can see, the numbers between 0 & 9 are the same as decimal system. However after that, 10 is represented by A. 11 by B, 12 by C and so on. This goes on until the letter F which is used to represent the number 15.

So in hexadecimal system, we have symbols to count from 0 to 15!

## Why Do We Use Hexadecimal System?

Now that we know what hexadecimal system is, let us learn why we need it.

If you take a look at a computer, we know that it works in binary right? So the only numbers it can understand is 1s & 0s. Because of this, a large number like 10 is represented in binary as 1010b right?

But as you can see, it is not so readable. Correct? So there is a very good chance that we can read or write a binary number wrong! So to avoid that, we use hexadecimal numbers when working with computers!

So you can see few examples of hexadecimal numbers in the above table. Right? But did you notice something? We have prefixed hexadecimal numbers with “0x”. Why? Because that is a convention that will tell anyone to treat it as a hexadecimal number!

Categories

## How To Plot Histogram In Python Using Matplotlib

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

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

## Plot Histogram In Python Using Matplotlib – The Basics

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

### What is an Histogram?

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

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

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

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

### What are Histogram bins?

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

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

## Plot Histogram In Python Using Matplotlib – Example

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

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

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

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

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

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

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

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

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

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

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

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

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

### Matplotlib Histogram Bins

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

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

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

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

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

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

So see you in the next article!

Categories

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

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

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

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

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

``````import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x], '*')
plt.plot(x, [xi*2 for xi in x], '+')
plt.plot(x, [xi*3 for xi in x], 'm^')
plt.show()``````

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

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

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

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

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

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

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

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

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

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

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

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

Well, take a look at it yourself below:

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

``````import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x], '*')
plt.plot(x, [xi*2 for xi in x], '+')
plt.plot(x, [xi*3 for xi in x], color='yellow', marker='^', markeredgecolor='green', markerfacecolor='red')
plt.show()``````

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

## Conclusion

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

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

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

Categories

## How To Change Marker Color In Matplotlib

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

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

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

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

How To Change Marker Style In Matplotlib

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

Here is how the plot then looks like:

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

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

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

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

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

## Change Marker Color In Matplotlib

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

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

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

Well, luckily we can do that! How? By passing our desired color value to the plot( ) function. So the code for that will then look like this:

``````import matplotlib.pyplot as plt
x = range(1, 10)
plt.plot(x, [xi*1 for xi in x], '*')
plt.plot(x, [xi*2 for xi in x], '+')
plt.plot(x, [xi*3 for xi in x], 'm^')
plt.show()``````

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

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

So what do you see?!

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

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

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

So until next time, take care!