Learn how to create bar charts in Python using Matplotlib to visually compare discrete categories and their associated values.
What it is
A bar chart (or column chart) is a graphical representation that uses rectangular bars to show the magnitude of categorical data. The length or height of each bar is proportional to the value it represents. In Python, this is primarily handled by the matplotlib.pyplot.bar() function. Key related terms include x-axis (categories), y-axis (values), and labels.
Why it matters
- Comparison: It allows for quick visual comparison between different groups or categories.
- Simplicity: Unlike line charts, bar charts do not imply continuity, making them ideal for discrete data like product sales or survey responses.
- Readability: Humans are naturally good at judging lengths, making differences in values easy to spot.
- Flexibility: Bars can be oriented vertically or horizontally to fit layout constraints.
Syntax or steps
The basic syntax requires two main arguments: a sequence of category labels and a sequence of corresponding values.
plt.bar(x, height)
Where x defines the positions of the bars (usually strings or numbers) and height defines the length of the bars.
Example
Below is a complete script comparing fruit sales.
import matplotlib.pyplot as plt
# Data
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [150, 90, 200, 60]
# Create the bar chart
plt.figure(figsize=(8, 5))
bars = plt.bar(fruits, sales, color='skyblue')
# Add titles and labels
plt.title('Fruit Sales Comparison')
plt.xlabel('Fruit Type')
plt.ylabel('Units Sold')
# Optional: Add value labels on top of bars
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{int(height)}',
ha='center', va='bottom')
plt.show()
Explanation: We import matplotlib.pyplot. We define lists for categories (fruits) and values (sales). plt.bar() draws the chart. We use a loop with bar.get_height() to place text annotations directly above each bar for precise reading.
Common mistakes
- Mismatched lengths: If the list of categories and the list of values have different lengths, Matplotlib will raise an error. Ensure both lists contain the same number of elements.
- Forgetting
plt.show(): Without callingplt.show(), the plot may not render in interactive environments or scripts. - Using continuous data incorrectly: Bar charts are for discrete categories. If your x-axis represents time with many points, a line chart is usually more appropriate.
- Ignoring axis limits: By default, the y-axis starts at zero. This is correct for bar charts because the area/length must represent the value proportionally. Never truncate the y-axis start unless you are using a specialized visualization technique.
When to use it
Compare bar charts with line charts based on data type.
| Chart Type | Best For | Data Nature |
|---|---|---|
| Bar Chart | Comparing distinct categories (e.g., countries, products). | Discrete / Categorical |
| Line Chart | Trends over time or ordered sequences. | Continuous / Temporal |
Practice
Guided Exercise: Modify the example above to change the bar color to 'coral' and rotate the x-axis labels by 45 degrees using plt.xticks(rotation=45).
Challenge: Create a horizontal bar chart using plt.barh() instead of plt.bar(). Note that the axes swap roles.
Quick check
Question: Why should the y-axis of a standard bar chart always start at zero?
Answer: Because the visual encoding relies on the length of the bar. Starting at a non-zero value distorts the ratio between bars, misleading the viewer about the relative differences.
Summary
Bar charts are essential for comparing discrete categories. Use plt.bar() for vertical comparisons and ensure your data lists match in length. Always keep the baseline at zero to maintain accurate visual proportions.