Basic Bar Chart
Create a simple bar chart:
import matplotlib.pyplot as plt
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]
plt.bar(categories, values)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart')
plt.show()
Horizontal Bar Chart
Create horizontal bars:
plt.barh(categories, values)
plt.xlabel('Values')
plt.ylabel('Categories')
plt.title('Horizontal Bar Chart')
plt.show()
Customizing Bars
Customize bar appearance:
plt.bar(categories, values,
color='blue', # Bar color
edgecolor='black', # Edge color
linewidth=2, # Edge width
alpha=0.7, # Transparency
width=0.8) # Bar width
Multiple Bar Groups
Compare multiple groups:
import numpy as np
categories = ['A', 'B', 'C', 'D']
values1 = [10, 20, 15, 25]
values2 = [15, 25, 20, 30]
x = np.arange(len(categories))
width = 0.35
plt.bar(x - width/2, values1, width, label='Group 1')
plt.bar(x + width/2, values2, width, label='Group 2')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Grouped Bar Chart')
plt.xticks(x, categories)
plt.legend()
plt.show()
Stacked Bar Chart
Stack bars on top of each other:
bottom_values = [10, 20, 15, 25]
top_values = [5, 10, 8, 12]
plt.bar(categories, bottom_values, label='Bottom')
plt.bar(categories, top_values, bottom=bottom_values, label='Top')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Stacked Bar Chart')
plt.legend()
plt.show()
Color Mapping
Color bars based on values:
import matplotlib.cm as cm
colors = cm.viridis(values / max(values))
plt.bar(categories, values, color=colors)
plt.show()
Best Practices
- Use appropriate orientation: Horizontal for long labels
- Choose colors wisely: Use colorblind-friendly palettes
- Add value labels: Show exact values on bars
- Order bars: Sort by value for easier comparison
Next Steps
Learn about line plots or scatter plots.