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.
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.
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()
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()
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.
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.
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.
plt.title("My Chart")
plt.xlabel("X axis")
plt.ylabel("Y axis")
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.
plt.plot(x, y, label="Series 1")
plt.legend()
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.
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)
| 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 |
| 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 |
plt.show(), after which no chart appears on the screen.plt.savefig() after plt.show(), which can save a blank image in some environments.plt.bar() for continuous data and plt.hist() for categorical data; they are not interchangeable.plt.plot(), giving x-values and y-values swapped.% in autopct="%1.1f%%", which produces formatting errors or wrong labels on pie sectors.plt.xlabel without parentheses, which does nothing because the function is not called.plt.legend(), so the chart shows multiple lines without labels.matplotlib.pyplot as plt at the top of the program.plt.xlim() where the minimum is greater than the maximum, which shows an empty or inverted axis.plt.plot() is for lines, plt.bar() for vertical bars, plt.scatter() for points, plt.hist() for frequencies, and plt.pie() for sectors.plt.show().kind="bar" on a pandas Series or DataFrame works with s.plot(kind="bar") for quick charts.bins in a histogram controls the number of intervals and larger values give a finer chart.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.