Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Plotting Histogram in Python using Matplotlib
Next article icon

ABarplotis a graph that represents the relationship between a categoric and a numeric feature. Many rectangular bars correspond to each category of the categoric feature and the size of these bars represents the corresponding value. Using grouped bar plots,  we can study the relationship between more than two features.

In Python, we can plot a barplot either using theMatplotliblibrary or using theseabornlibrary, which is a higher-level library built on Matplotlib and it also supportspandasdata structures. In this article, we have used seaborn.barplot() function to plot the grouped bar plots.

Another important aspect of data visualization using bar plots is, using annotations i.e adding text for a better understanding of the chart. This can be achieved by using theannotate() function in pyplot module of matplotlib library as explained in the below steps.

Step 1:Importing the libraries and the dataset used. Here we have used the Titanic dataset, which is inbuilt with seaborn. 

Python3
# importing the libraries usedimportseabornassnsimportmatplotlib.pyplotasplt# Importing the datasetdf=sns.load_dataset("titanic")print(df.head())

Output:

Original Dataset

We will plot a grouped bar plot to analyze the average age and count of travelers on titanic, gender-wise in different ticket classes. For that, we need to transform the dataset.

Step 2:Transforming the dataset using grouping and aggregation on the original dataset.

Python3
# transforming the dataset for barplotdata_df=df.groupby(['sex','class']).agg(avg_age=('age','mean'),count=('sex','count'))data_df=data_df.reset_index()print(data_df.head())

Output:

transformed dataset

Explanation:Grouped bar plots require at least two categorical features and a numerical feature. Here, we have filtered out the 'class' feature to categorize and the 'sex' feature to group the bars usingpandas.Dataframe.groupby() function. Then we have aggregated the mean age and count for each group usingpandas.core.groupby.DataFrameGroupBy.agg(). Previous operations resulted in a multi-index dataframe, hence we reset the index to obtain the dataset shown below.

Step 3:Now, we plot a simple Barplot using the transformed dataset using seaborn.barplot() function. 

Python3
# code to plot a simple grouped barplotplt.figure(figsize=(8,6))sns.barplot(x="class",y="avg_age",hue="sex",data=data_df,palette='Greens')plt.ylabel("Average Age",size=14)plt.xlabel("Ticket Class",size=14)plt.title("Simple Grouped Barplot",size=18)

Output :

Note that, We have used 'hue' keyword argument to group the bars based on 'sex' feature.

Step 4:Annotating the bars

Python3
# code for annotated grouped barplotplt.figure(figsize=(8,6))splot=sns.barplot(x="class",y="avg_age",hue="sex",data=data_df,palette='Greens')forpinsplot.patches:splot.annotate(format(p.get_height()),(p.get_x()+p.get_width()/2.,p.get_height()),ha='center',va='center',xytext=(0,9),textcoords='offset points')plt.ylabel("Average Age",size=14)plt.xlabel("Ticket Class",size=14)plt.title("Grouped Barplot with annotations",size=18)

Output:

Explanation:In the above code, we have used the 'patches' attribute of the seaborn plot object to iterate over each bar. We have calculated the height, coordinates, and put text using theannotatefunction for each bar.

Step 5:Since each bar represents age and putting decimal doesn't make its value sensible. We will customize our text by rounding off to the nearest integer and then using the format() function as shown in the code below.

Python3
# code for annotated barplotplt.figure(figsize=(8,6))splot=sns.barplot(x="class",y="avg_age",hue="sex",data=data_df,palette='Greens')plt.ylabel("Average Age",size=14)plt.xlabel("Ticket Class",size=14)plt.title("Grouped Barplot with annotations",size=18)forpinsplot.patches:splot.annotate(format(round(p.get_height()),'.0f')+"Years",(p.get_x()+p.get_width()/2.,p.get_height()),ha='center',va='center',size=14,xytext=(0,-12),textcoords='offset points')

Output:

Also, by changing the coordinates we have shifted our text inside the bar. 


Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp