Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to plot a bar graph in Matplotlib from a Pandas series?
To plot a bar graph from a Pandas Series in Matplotlib, you can use the built-in plot() method with kind="bar". This creates clean visualizations directly from your data without manually handling x-axis labels or positioning.
Steps to Create a Bar Plot
Create a Pandas Series with your data
Use the
plot()method withkind="bar"Display the plot using
plt.show()
Basic Bar Plot from Series
Here's how to create a simple bar plot from a Pandas Series ?
import pandas as pd
import matplotlib.pyplot as plt
# Create a Series
data = pd.Series([25, 35, 15, 40, 30],
index=['A', 'B', 'C', 'D', 'E'])
# Plot bar graph
data.plot(kind='bar', title='Sample Bar Plot')
plt.ylabel('Values')
plt.show()
Bar Plot from DataFrame
You can also create multiple bar plots from a DataFrame ?
import pandas as pd
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
# Create data dictionary
data = {
'Sales Q1': [120, 150, 180, 90, 200],
'Sales Q2': [130, 160, 170, 110, 190],
'Sales Q3': [140, 140, 190, 120, 210]
}
# Create DataFrame
df = pd.DataFrame(data, index=['Jan', 'Feb', 'Mar', 'Apr', 'May'])
# Create bar plot
df.plot(kind='bar', title='Quarterly Sales Comparison')
plt.ylabel('Sales Amount')
plt.xlabel('Months')
plt.xticks(rotation=45)
plt.show()
Customizing Bar Plots
Add colors, transparency, and styling to enhance your visualization ?
import pandas as pd
import matplotlib.pyplot as plt
# Create Series
scores = pd.Series([88, 92, 79, 94, 86],
index=['Math', 'Science', 'English', 'History', 'Art'])
# Create customized bar plot
ax = scores.plot(kind='bar',
color=['skyblue', 'lightgreen', 'salmon', 'gold', 'plum'],
alpha=0.7,
title='Student Scores by Subject')
ax.set_ylabel('Score')
ax.set_xlabel('Subjects')
plt.xticks(rotation=0)
plt.grid(axis='y', alpha=0.3)
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
kind |
Plot type | 'bar', 'barh' |
color |
Bar colors | 'red', ['blue', 'green'] |
alpha |
Transparency | 0.7 |
title |
Plot title | 'My Bar Chart' |
Conclusion
Use Series.plot(kind='bar') for simple bar plots and DataFrame.plot(kind='bar') for grouped bars. Customize with colors, transparency, and labels to create professional visualizations from your Pandas data.
