How to fill color by groups in histogram using Matplotlib?
In this article, we are going to see how to fill color by the group in the histogram using Matplotlib in Python.
Method 1: Using pivot() method
In this method, we are going to use the pivot method which returns an organized DataFrame based on specified index/column values.
Syntax: DataFrameName.pivot(index=’indexLabel’, columns=’columnLabel’, values=’columnName’)
Note: This approach is followed when we want to perform further grouping on the given data.
We use this DataFrame in this approach to plot a histogram representing ages between different genders.
Here the original DataFrame is reorganized the Age values based on the Gender column into a new DataFrame. To this reorganized DataFrame we plotted histogram.
The resultant plot indicates there are 2 females between the age 18-20, 1 female is in the age 29-30 and 1 male between 20-22 i.e., 21 and finally 1 male is between 24-25.
Method 2: Using separated dataset
This method can be followed when we already have separated data on any basis. Let’s consider 2 objects that hold the age of males and females.
If we have the above kind of separated data then we can specify different colors to the different groups while plotting histogram i.e., in hist method.
As we already have grouped data based on gender we no need to use any pivot function. So we can directly specify those separate sets of data with different colors in hist function.
These are the two approaches that need to be followed based on the given data and requirement to fill color by groups in the histogram.