0
0
MatplotlibHow-ToBeginner ยท 3 min read

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 x and height lists, 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 width too 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:

ParameterDescriptionDefault
xPositions or labels on x-axisRequired
heightHeights of the barsRequired
widthWidth of each bar0.8
colorColor of barsNone (default color cycle)
labelLabel for legendNone
โœ…

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.