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
Selected Reading
How to plot a bar chart for a list in Python matplotlib?
To plot a bar chart for a list in Python matplotlib, we can use the plt.bar() function. A bar chart displays categorical data with rectangular bars whose heights represent the values.
Basic Bar Chart
Here's how to create a simple bar chart from a list of values ?
import matplotlib.pyplot as plt
# List of data points
data = [5, 3, 8, 2, 7, 4, 6]
# Create bar chart
plt.bar(range(len(data)), data)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart from List')
plt.show()
Bar Chart with Custom Labels
You can add custom labels for better readability ?
import matplotlib.pyplot as plt
# Data and labels
values = [25, 30, 15, 40, 35]
categories = ['A', 'B', 'C', 'D', 'E']
# Create bar chart with labels
plt.bar(categories, values, color='skyblue')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart with Custom Labels')
plt.show()
Customizing Bar Chart Appearance
You can customize colors, width, and other properties ?
import matplotlib.pyplot as plt
# Sample data
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
sales = [120, 150, 180, 90, 200]
# Create customized bar chart
plt.figure(figsize=(8, 5))
bars = plt.bar(months, sales,
color=['red', 'blue', 'green', 'orange', 'purple'],
width=0.6,
edgecolor='black',
linewidth=1)
# Add value labels on bars
for bar, value in zip(bars, sales):
plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 5,
str(value), ha='center', va='bottom')
plt.xlabel('Months')
plt.ylabel('Sales')
plt.title('Monthly Sales Bar Chart')
plt.grid(axis='y', alpha=0.3)
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
x |
X-axis positions | range(len(data)) |
height |
Bar heights (values) | data |
color |
Bar colors |
'red' or ['red', 'blue']
|
width |
Bar width |
0.8 (default) |
Conclusion
Use plt.bar() to create bar charts from lists. Customize with colors, labels, and styling for better visualization. Always add axis labels and titles for clarity.
Advertisements
