0
0
Matplotlibdata~5 mins

Histogram vs bar chart distinction in Matplotlib

Choose your learning style9 modes available
Introduction

We use histograms and bar charts to show data, but they show different things. Histograms show how data is spread out in groups, while bar charts compare separate categories.

You want to see how many people fall into age groups in a survey.
You want to compare sales numbers for different products.
You want to understand the distribution of test scores in a class.
You want to show the count of different types of fruits sold.
You want to check how data values are spread over ranges.
Syntax
Matplotlib
import matplotlib.pyplot as plt

# Histogram
plt.hist(data, bins=number_of_bins)

# Bar chart
plt.bar(categories, values)

Histograms use continuous data divided into bins (ranges).

Bar charts use separate categories with individual bars.

Examples
This shows how ages are spread in 5 groups.
Matplotlib
import matplotlib.pyplot as plt

# Histogram example
ages = [22, 25, 27, 30, 35, 40, 45, 50, 55, 60]
plt.hist(ages, bins=5)
plt.show()
This compares counts of different fruits.
Matplotlib
import matplotlib.pyplot as plt

# Bar chart example
fruits = ['Apple', 'Banana', 'Cherry']
counts = [10, 15, 7]
plt.bar(fruits, counts)
plt.show()
Sample Program

This program draws a histogram to show how ages are grouped and a bar chart to compare fruit sales side by side.

Matplotlib
import matplotlib.pyplot as plt

# Data for histogram: ages of people
ages = [22, 25, 27, 30, 35, 40, 45, 50, 55, 60, 22, 25, 27, 30, 35]

# Data for bar chart: fruit sales
fruits = ['Apple', 'Banana', 'Cherry']
sales = [10, 15, 7]

# Create histogram
plt.figure(figsize=(10,4))
plt.subplot(1,2,1)
plt.hist(ages, bins=5, color='skyblue', edgecolor='black')
plt.title('Histogram of Ages')
plt.xlabel('Age groups')
plt.ylabel('Number of people')

# Create bar chart
plt.subplot(1,2,2)
plt.bar(fruits, sales, color='lightgreen', edgecolor='black')
plt.title('Bar Chart of Fruit Sales')
plt.xlabel('Fruit')
plt.ylabel('Sales count')

plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Histograms group data into ranges, so bars touch each other.

Bar charts show separate categories, so bars have spaces between them.

Always label axes clearly to help understand the chart.

Summary

Histograms show data distribution in continuous ranges.

Bar charts compare values across distinct categories.

Use histograms for numeric data spread, bar charts for category comparisons.