๐Ÿ“˜ CodingMarble Learn

Data Visualization with Matplotlib: Line, Bar and Histogram

Data visualization means showing data as pictures such as charts, so that patterns are easy to see. In Python we use the pyplot module of Matplotlib, imported as plt. A line plot shows change over time, a bar graph compares separate groups and a histogram shows how values are spread over ranges called bins. A chart becomes clear with a title, axis labels and a legend, and plt.savefig() saves it as an image file.

๐ŸŽฌ Step-by-step story

  1. A chart shows in one look what a table of numbers hides.
  2. A line plot joins points in order: best for change over time.
  3. A bar graph compares separate groups: tallest bar = biggest value.
  4. A histogram drops each value into a range (bin) and counts them.
  5. Title, x and y labels and legend make a chart clear; savefig saves it.
  6. Your turn: switch chart type and bins to see the same data differently.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

๐Ÿค” Common doubts, cleared

Why draw a chart when I already have the table?

The table has the same numbers, but your eyes must compare them one by one. A chart shows the rise, fall and biggest value at once.

When is a line plot wrong?

When the x-values are not in an order (like subject names), joining them with a line suggests a trend that does not exist. Use bars instead.

Why do bars in a bar graph have gaps?

Each bar is a separate group. The gap shows they are not connected ranges.

What is a bin?

A bin is one range of values, like 58 to 72. A histogram counts how many values fall in each bin.

Where does a value exactly on a bin edge go?

Into the bin on its right, except the very last edge, which belongs to the last bin.

Why is my saved image blank?

You saved after plt.show(). Call plt.savefig() first, then show().

Does the shape of a histogram depend on bins?

Yes. Few bins hide detail; too many bins make it bumpy. Try 2, 5 and 7 in step 6.

Purpose of plotting

Data visualization means turning numbers into pictures such as charts and graphs. We plot data because:

import matplotlib.pyplot as plt   # pyplot = the plotting part of Matplotlib

Every chart follows the same idea: make the chart, decorate it, then plt.show() or plt.savefig().

Line plot

A line plot marks points and joins them in order. Use it when the x-axis is time or order (days, months, years).

month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [20, 35, 30, 45, 50, 60]
plt.plot(month, sales, color='b', marker='o', linestyle='-', linewidth=2)
plt.show()

Options: color (e.g. 'r', 'green'), marker ('o', '*', 's'), linestyle ('-', '--', ':'), linewidth, markersize.

Bar graph

A bar graph draws one bar per group. The height shows the value. Use it to compare separate things (subjects, cities, products).

subject = ['Eng', 'Hindi', 'Maths', 'Sci', 'SSt']
marks = [78, 85, 92, 70, 88]
plt.bar(subject, marks, color='teal', width=0.6)
plt.barh(subject, marks)     # horizontal bars
plt.show()

Histogram

A histogram shows how values are spread. The range of data is cut into equal parts called bins. Each value falls into one bin, and the bar height is how many values fell there (the frequency). Bars touch each other, because the ranges are continuous.

marks = [35,42,48,51,55,58,61,63,66,68,72,74,79,85,93]
plt.hist(marks, bins=[30,44,58,72,86,100], edgecolor='black')
plt.hist(marks, bins=5)     # 5 equal bins from min to max

A value on an edge (like 58) goes into the bin on its right; only the last bin includes its right edge. histtype='step' draws just the outline.

Bar graph or histogram?

Bar graph: separate groups, gaps between bars, any order. Histogram: one number column cut into ranges, no gaps, fixed order.

Title, labels and legend

plt.plot(month, shopA, label='Shop A')
plt.plot(month, shopB, label='Shop B')
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales (in thousand โ‚น)')
plt.legend()          # shows the label= names in a box
plt.grid(True)
plt.show()

A legend is the small key that tells which colour is which line. It needs label= in each plot call. plt.xticks() and plt.yticks() change the marks on the axes.

Plotting straight from pandas

df.plot(kind='line', x='Month', y='Sales')
df.plot(kind='bar', x='Subject', y='Marks')
df['Marks'].plot(kind='hist', bins=5)

Saving plots

plt.savefig('sales.png')                 # PNG image in the current folder
plt.savefig('c:/charts/sales.pdf')       # PDF, full path
plt.savefig('sales.jpg', dpi=150)

Call savefig() before plt.show(). After show() closes, the figure is empty and you save a blank picture.

Try it: chart your week

Write down how many minutes you spend on your phone each day for 7 days. Make a line plot (days vs minutes) with a title, labels and savefig('week.png'). Then ask 10 friends their height in cm and draw a histogram with 4 bins. Before running, guess which bin will be tallest. In the 3D, step 6, switch bins between 2, 5 and 7 and notice how the shape changes.

Key formulas and definitions

Worked examples

1. Which chart suits (a) temperature over 7 days, (b) marks in 5 subjects, (c) heights of 40 students?

(a) line plot (change over time), (b) bar graph (separate groups), (c) histogram (spread of one number column).

2. Write code for a red dashed line plot of year [2021, 2022, 2023, 2024] against students [300, 340, 390, 420] with circle markers.

plt.plot([2021,2022,2023,2024], [300,340,390,420], color='r', linestyle='--', marker='o'); plt.show()

3. Draw a bar graph of fruits ['Apple','Mango','Banana'] sold [40, 65, 30] with title 'Fruit Sales' and axis labels.

plt.bar(['Apple','Mango','Banana'], [40,65,30]); plt.title('Fruit Sales'); plt.xlabel('Fruit'); plt.ylabel('Units sold'); plt.show()

4. marks = [35,42,48,51,55,58,61,63,66,68,72,74,79,85,93] with bins=[30,44,58,72,86,100]. Find the frequency of each bin.

30โ€“44: 35, 42 โ†’ 2. 44โ€“58: 48, 51, 55 โ†’ 3. 58โ€“72: 58, 61, 63, 66, 68 โ†’ 5. 72โ€“86: 72, 74, 79, 85 โ†’ 4. 86โ€“100: 93 โ†’ 1. Total 15.

5. Plot sales of Shop A and Shop B on one chart with a legend and save it as 'compare.png'.

plt.plot(month, a, label='Shop A'); plt.plot(month, b, label='Shop B'); plt.legend(); plt.savefig('compare.png'); plt.show()

6. A student wrote plt.show() and then plt.savefig('x.png'). The file is blank. Why, and how to fix?

show() displays and then clears the figure, so savefig saved an empty figure. Put savefig() before show().

Common mistakes

Practice quiz

1. Which module of Matplotlib is used for plotting?
2. Best chart for monthly rainfall over a year:
3. plt.hist() shows:
4. The legend needs which argument in plt.plot()?
5. Which function saves a chart as an image?

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is data visualization in Class 12 IP?

It is showing data as charts using Matplotlib's pyplot module, so patterns and comparisons are easy to see.

What is the difference between a bar graph and a histogram?

A bar graph compares separate groups with gaps between bars; a histogram shows how one numeric variable is spread over continuous bins with touching bars.

How do you save a plot in Matplotlib?

Use plt.savefig('name.png') before plt.show(); the extension decides the format (png, jpg, pdf).

Where this is taught

CBSE (India)Class 12Data Handling using Pandas and Data Visualization

Learn first

Learn next

Related lessons

All Informatics Practices lessons