w3resource

Creating a Grouped Bar Plot for Multiple Categories Using Pandas

Pandas: Visualization Integration Exercise-10 with Solution

Write a Pandas program to create a grouped bar plot for multiple categories.

This exercise shows how to create a grouped bar plot for multiple categories using Pandas and Matplotlib.

Sample Solution :

Code :

import pandas as pd
import matplotlib.pyplot as plt

# Create a sample DataFrame
df = pd.DataFrame({
    'Category': ['A', 'B', 'C'],
    'Product_A': [50, 80, 30],
    'Product_B': [40, 60, 20]
})

# Create a bar plot for multiple products
df.plot(kind='bar', x='Category', y=['Product_A', 'Product_B'], figsize=(8, 5))

# Add a title
plt.title('Product A and B Sales by Category')

# Display the plot
plt.show()

Output:

Pandas - Bar Plot with Multiple Categories Using Pandas

Explanation:

  • Created a DataFrame with sales data for two products across different categories.
  • Used plot(kind='bar') to create a grouped bar plot showing both 'Product_A' and 'Product_B' sales by category.
  • Added a title and displayed the plot.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/pandas-create-a-grouped-bar-plot-for-multiple-categories.php