How to Create Bar Chart in Matplotlib: Simple Guide
To create a bar chart in
matplotlib, use the plt.bar() function with lists or arrays for the x-axis labels and their corresponding heights. Customize the chart by adding labels, title, and colors as needed.Syntax
The basic syntax for creating a bar chart in Matplotlib is:
plt.bar(x, height, width=0.8, color=None, label=None)
Here, x is the sequence of positions or labels on the x-axis, height is the sequence of bar heights, width controls the bar thickness, color sets bar colors, and label adds a legend label.
python
import matplotlib.pyplot as plt x = ['A', 'B', 'C'] height = [1, 2, 3] plt.bar(x, height, width=0.8, color=None, label=None) plt.xlabel('X-axis label') plt.ylabel('Y-axis label') plt.title('Bar Chart Title') plt.legend() plt.show()
Example
This example shows how to create a simple bar chart with categories on the x-axis and their values as bar heights. It also adds labels and a title.
python
import matplotlib.pyplot as plt categories = ['Apples', 'Bananas', 'Cherries', 'Dates'] values = [10, 15, 7, 12] plt.bar(categories, values, color='skyblue') plt.xlabel('Fruit') plt.ylabel('Quantity') plt.title('Fruit Quantity Bar Chart') plt.show()
Output
A bar chart with four bars labeled Apples, Bananas, Cherries, Dates on the x-axis and their quantities as heights.
Common Pitfalls
Common mistakes when creating bar charts include:
- Passing mismatched lengths for
xandheightlists, causing errors. - Using numeric x values without setting proper labels, resulting in unclear charts.
- Not calling
plt.show()to display the chart. - Overlapping bars by setting
widthtoo large or using multiple bar sets without adjusting positions.
python
import matplotlib.pyplot as plt # Wrong: mismatched lengths # plt.bar(['A', 'B'], [1, 2, 3]) # This will cause an error # Right: matching lengths plt.bar(['A', 'B', 'C'], [1, 2, 3]) plt.show()
Output
A bar chart with three bars labeled A, B, C with heights 1, 2, and 3 respectively.
Quick Reference
Here is a quick reference for key plt.bar() parameters:
| Parameter | Description | Default |
|---|---|---|
| x | Positions or labels on x-axis | Required |
| height | Heights of the bars | Required |
| width | Width of each bar | 0.8 |
| color | Color of bars | None (default color cycle) |
| label | Label for legend | None |
Key Takeaways
Use plt.bar(x, height) with matching lengths to create a bar chart.
Add labels and title for clarity using plt.xlabel(), plt.ylabel(), and plt.title().
Always call plt.show() to display the chart.
Avoid mismatched data lengths and unclear x-axis labels.
Customize bar colors and width for better visuals.