ByteBoard Notes Notes

Plot a histogram of the marks of a class

Informatics Practices XII · Experiment 21 of 38 · Pandas

12-IPMatplotlib programs
Expt. No.21
Page No.42

Histogram of marks

Aim

To write a Python program that plots a histogram showing how the marks of 30 students are distributed across ranges.

Concepts used

Algorithm

  1. Store 30 marks in a list.
  2. Choose bin edges 30, 40, 50 … 100.
  3. Draw the histogram with plt.hist() and black edges.
  4. Add axis labels and a title, and show the chart.

Program

# Histogram of the marks of a class import matplotlib.pyplot as plt marks = [45, 67, 89, 72, 55, 38, 91, 64, 77, 82,         59, 68, 73, 49, 85, 95, 62, 70, 58, 66,         79, 88, 53, 41, 74, 69, 81, 60, 57, 76]plt.hist(marks, bins=[30, 40, 50, 60, 70, 80, 90, 100], edgecolor="black")plt.xlabel("Marks")plt.ylabel("Number of students")plt.title("Distribution of marks")plt.show()

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python plot_histogram.py
(no printed output)
Figure 1
Histogram of 30 students' marks in 10-mark bins from 30 to 100; the 60-70 and 70-80 bins are tallest with 7 students each.

✓ Printed by running this program, not typed by hand.

Result

Each bar counts the students in one 10-mark range. The 60–70 and 70–80 ranges have the tallest bars, so most students scored between 60 and 80.

Viva voce: what the examiner may ask

01How is a histogram different from a bar chart?

A histogram shows how numeric data is spread across ranges (bins) with no gaps; a bar chart compares separate categories.

02What does the bins argument set?

The number of ranges, or (as a list) their edges.

03In which bin does a mark of exactly 70 fall?

In 70–80: each bin includes its left edge, and only the last bin includes its right edge.

Variations for the lab test

  1. Use bins=5 and compare the chart.
  2. Change the colour of the bars.
  3. Plot the histogram of the IP marks from experiment 15.
! Common mistake Passing the list of bin edges as the data and the marks as bins swaps their meanings and gives a meaningless chart.
Back to the 12-IP index