ЁЯТ╗
тМия╕П
ЁЯЦ▒я╕П
ЁЯЦея╕П
ЁЯТ╛
тЖР Back to Dashboard
Font Size:

1. Introduction

Data visualization is the graphical representation of data so that patterns, trends, and outliers become visible at a glance. While a table of numbers requires careful reading, a well-drawn chart communicates the same information almost instantly. In this chapter we learn to create charts using Matplotlib, the most widely used plotting library in Python, whose pyplot module provides a MATLAB-like interface for drawing graphs.

The chapter begins with the setup of the plotting environment, including how to import pyplot and how to create a figure with a single command. We then cover the major chart types required by the syllabus: line plots for trends over time, bar charts for comparing categories, scatter plots for the relationship between two variables, histograms for the distribution of one variable, and pie charts for showing parts of a whole. We also learn to customise charts with titles, axis labels, legends, grid lines, and colours, and finally how to save a figure as an image file.

Charts in the exam are usually written as short programs that build a plot from a given list or DataFrame. Questions may ask for the output appearance of the chart, the purpose of a particular function call, or how to label the axes. Understanding the one-to-one correspondence between each function call and the element it draws is therefore the key to scoring full marks in this chapter.

2. Importing Matplotlib

Matplotlib must be installed before it can be used. The installation command is pip install matplotlib. In programs, the plotting interface is imported as follows:

import matplotlib.pyplot as plt

The alias plt is standard. The function plt.show() displays the chart in a separate window, while in notebook environments charts are shown inline automatically. A basic line chart is drawn like this:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 5, 3]
plt.plot(x, y)
plt.show()

Here plt.plot(x, y) draws a line joining the points, and plt.show() renders it on the screen.

3. Line Chart

A line chart connects successive data points with straight lines and is ideal for showing trends over a continuous range such as time.

import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr"]
sales = [200, 240, 180, 260]
plt.plot(months, sales)
plt.title("Monthly Sales")
plt.xlabel("Months")
plt.ylabel("Sales in Rs")
plt.show()

The function plt.plot() takes the x-values and y-values as its first two arguments. The default colour is blue and the default marker is none, but the appearance can be changed with extra arguments:

plt.plot(months, sales, color="red", linestyle="--", marker="o")

Multiple lines can be drawn on the same chart by calling plt.plot() more than once before plt.show(). A legend is added with plt.legend() and labels are given inside each plot() call:

plt.plot(months, sales, label="2024")
plt.plot(months, sales2, label="2025")
plt.legend()
plt.show()

4. Bar Chart

A bar chart represents each category with a rectangle whose height (or length) is proportional to its value. It is used for comparing quantities across distinct categories.

import matplotlib.pyplot as plt
students = ["Class 11", "Class 12"]
count = [40, 35]
plt.bar(students, count)
plt.title("Student Count")
plt.show()

The function plt.bar() draws vertical bars. For horizontal bars, plt.barh() is used. To show exact values on top of the bars, the text can be added manually with plt.text():

import matplotlib.pyplot as plt
names = ["A", "B", "C"]
marks = [90, 85, 78]
plt.bar(names, marks, color=["red", "green", "blue"])
plt.xlabel("Student")
plt.ylabel("Marks")
plt.show()

A bar chart created from a pandas Series is equally simple because the Series index becomes the x-axis labels and the values the bar heights:

import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series([90, 85, 78], index=["A", "B", "C"])
s.plot(kind="bar")
plt.show()

5. Scatter Plot

A scatter plot places one point per observation at the coordinates given by two variables. It is used to investigate whether two variables are related, for example height and weight.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 5, 3]
plt.scatter(x, y)
plt.title("Scatter Plot")
plt.xlabel("X values")
plt.ylabel("Y values")
plt.show()

The scatter() function takes the same positional arguments as plot(), but instead of joining the points it draws a marker at each position. The default marker is a small circle; the argument marker changes its shape, for example marker="*" or marker="s" for squares.

6. Histogram

A histogram shows the distribution of a single continuous variable by grouping values into intervals called bins and drawing one bar per bin. The height of each bar is the frequency of values falling in that bin.

import matplotlib.pyplot as plt
marks = [45, 67, 89, 34, 78, 91, 56, 72, 65, 88]
plt.hist(marks, bins=5)
plt.title("Marks Distribution")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.show()

The bins argument controls the number of intervals. A larger number of bins gives a finer, more detailed histogram while a smaller number gives a coarser one. Unlike a bar chart, a histogram is used for continuous data and the bars are usually drawn touching each other.

7. Pie Chart

A pie chart divides a circle into sectors whose angles are proportional to the values they represent. It is used when we want to show how a total is shared among a few categories.

import matplotlib.pyplot as plt
subjects = ["Maths", "Science", "English", "Computers"]
hours = [6, 5, 3, 4]
plt.pie(hours, labels=subjects, autopct="%1.1f%%")
plt.title("Study Hours")
plt.show()

The labels argument gives a name to each sector and autopct displays the percentage of each sector on the chart. If the sectors do not add up to 100 percent, pyplot automatically scales them so that the circle is complete.

8. Customising Charts

8.1 Titles and Axis Labels

plt.title("My Chart")
plt.xlabel("X axis")
plt.ylabel("Y axis")

8.2 Grid Lines and Axis Limits

plt.grid(True)
plt.xlim(0, 10)
plt.ylim(0, 100)

plt.grid(True) draws grid lines, and plt.xlim() and plt.ylim() set the minimum and maximum values shown on the respective axes.

8.3 Legend

plt.plot(x, y, label="Series 1")
plt.legend()

8.4 Saving the Figure

plt.savefig("chart.png")

savefig() stores the current chart as an image file with the given name. It must be called before plt.show() because show() clears the figure in some environments.

8.5 Adding a Figure

By default pyplot creates a single current figure. Multiple figures can be created with plt.figure(num):

plt.figure(1)
plt.plot(x, y)
plt.figure(2)
plt.plot(a, b)

Quick Revision Tables

Table 1: Plotting Functions and Their Uses

Function Chart Type Best Used For
plt.plot() Line chart Trends over time
plt.bar() Bar chart Comparing categories
plt.scatter() Scatter plot Relationship of two variables
plt.hist() Histogram Distribution of one variable
plt.pie() Pie chart Parts of a whole

Table 2: Common Customisation Functions

Function Purpose
plt.title() Sets chart title
plt.xlabel() Labels X axis
plt.ylabel() Labels Y axis
plt.grid(True) Shows grid lines
plt.legend() Shows legend
plt.xlim(a, b) Sets X axis limits
plt.ylim(a, b) Sets Y axis limits
plt.savefig("file.png") Saves chart as image

Mind Map

graph TD A["Data Visualization"] --> B["Matplotlib pyplot"] A --> C["Chart Types"] A --> D["Customisation"] B --> B1["import matplotlib.pyplot as plt"] B --> B2["plt.show()"] C --> C1["Line: plt.plot"] C --> C2["Bar: plt.bar"] C --> C3["Scatter: plt.scatter"] C --> C4["Histogram: plt.hist"] C --> C5["Pie: plt.pie"] D --> D1["title, xlabel, ylabel"] D --> D2["grid, xlim, ylim"] D --> D3["legend, color, marker"] D --> D4["savefig"]

Important Diagrams (SVG)

Diagram 1: Choosing the Right Chart Type

Choosing the Right Chart Data Question What do we want to show? Trend over time Line chart plt.plot(x, y) e.g. sales by month Compare categories Bar chart plt.bar(x, y) e.g. marks of students Two-variable relation Scatter plot plt.scatter(x, y) e.g. height vs weight Distribution Histogram plt.hist(x, bins=n) e.g. marks frequency Parts of a whole Pie chart plt.pie(x, labels) e.g. budget share Remember the Difference Bar chart: categorical data, bars do not touch Histogram: continuous data grouped into bins, bars touch Golden Rule Match the chart to the question: trend, comparison, relation, distribution, or share

Diagram 2: Anatomy of a Matplotlib Chart

Anatomy of a Matplotlib Chart Chart Title X Axis Y Axis data points plt.xlabel("X Axis") and plt.ylabel("Y Axis") label the axes Golden Rule A complete chart has a title, labelled axes, and a legend; write these before plt.show()

Common Mistakes

  1. Forgetting to call plt.show(), after which no chart appears on the screen.
  2. Calling plt.savefig() after plt.show(), which can save a blank image in some environments.
  3. Using plt.bar() for continuous data and plt.hist() for categorical data; they are not interchangeable.
  4. Passing a list of strings and a list of numbers in the wrong order to plt.plot(), giving x-values and y-values swapped.
  5. Forgetting the % in autopct="%1.1f%%", which produces formatting errors or wrong labels on pie sectors.
  6. Using plt.xlabel without parentheses, which does nothing because the function is not called.
  7. Drawing multiple series but forgetting plt.legend(), so the chart shows multiple lines without labels.
  8. Forgetting to import matplotlib.pyplot as plt at the top of the program.
  9. Setting axis limits with plt.xlim() where the minimum is greater than the maximum, which shows an empty or inverted axis.

Exam Tips

  1. Practise writing the five basic chart programs from scratch, as one of them is almost guaranteed in the practical examination.
  2. Memorise that plt.plot() is for lines, plt.bar() for vertical bars, plt.scatter() for points, plt.hist() for frequencies, and plt.pie() for sectors.
  3. Know the order of steps: import, create data, call the chart function, add title and labels, then plt.show().
  4. Remember that kind="bar" on a pandas Series or DataFrame works with s.plot(kind="bar") for quick charts.
  5. Be ready to explain the difference between a bar chart and a histogram in one or two sentences.
  6. Learn that bins in a histogram controls the number of intervals and larger values give a finer chart.
  7. Practise predicting the output shape of simple charts described in words, e.g. a line chart of sales over months.

Conclusion

Data visualization completes the data-analysis workflow by turning processed numbers into meaningful pictures. The matplotlib.pyplot module provides a compact set of functions, one for each major chart type, and a shared collection of customisation tools. Line charts reveal trends, bar charts compare categories, scatter plots expose relationships, histograms summarise distributions, and pie charts illustrate shares of a whole. Titles, axis labels, legends, grid lines, and limits make a chart readable, while savefig() preserves it for reports. Combining these plotting skills with the pandas data-handling techniques from the earlier chapters allows a student to take raw data all the way from a CSV file to a finished, examinable analysis.