Home / Computer Science / Class XII / Plotting Data using Matplotlib
Plotting Data using Matplotlib — CUET Computer Science hero
Class XII 💻 Computer Science Ch 17 of 20

Plotting Data using Matplotlib

CUET unit: Plotting Data using Matplotlib

📌 Snapshot

  • Matplotlib charts decoded: line, bar, histogram, scatter, box and pie plots with labels and styling code.
  • Which chart answers which question, and how a title, axis labels, ticks and a legend make a plot readable.
  • Line style, marker, colour, bins, explode and autopct: the customising keywords CUET likes to test.
  • Pandas df.plot(kind=...) versus plt.plot(), and how to read a box plot with its median, whiskers and outliers.

📖 Detailed Notes

Written and reviewed by Rohit Singh, Computer Science & Commerce faculty at UniDrill (MCA, Osmania University · 6 years teaching). Based on NCERT Informatics Practices Class XII, Chapter 4.

Which is easier to read: 84 numbers or one picture?

A cultural mela records its sales for three weeks, seven days each. That is 21 numbers in a file. Ask "which day sells most?" and you start scanning. Draw the same numbers as a chart and the answer jumps out: the highest bar is Sunday. Data visualisation means showing data as a graph or chart, to see variation, to show relationships between variables and to communicate results to other people. Traffic symbols, a speedometer and a map in an atlas are everyday examples.

In Python the library for this is Matplotlib, and its drawing module is pyplot.

Code
import matplotlib.pyplot as plt

Here plt is just an alias (a short nickname). You could choose any other name, but plt is the convention and the one exam questions use. Install the library with pip install matplotlib.

Choosing the chart: the question decides

The right chart depends on the question and on the type of data. Learn this table first, because most CUET questions are "which plot for which job".

You want to… Chart pyplot function Pandas kind=
Show how a continuous value changes over time Line plot() 'line' (default)
Compare values across categories Bar bar() 'bar' (vertical), 'barh' (horizontal)
Show how often values fall in ranges Histogram hist() 'hist'
Show the relationship between two variables Scatter scatter() 'scatter'
Show the statistical summary and outliers Box boxplot() 'box'
Show parts of a whole Pie pie() 'pie'
Show how a total changes over time, filled in Area no direct pyplot function in this chapter 'area'

Anatomy of a plot

A figure is the whole window. Inside it sits the plotting area, with a title, an x label and a y label, ticks (the marks on each axis), optional grid lines and a legend (the key that links each colour to its data). Every pyplot function changes something in the current figure. A good chart always has a title, labelled axes and, when more than one series is drawn, a legend.

Function Job
plot(x, y) Draws x versus y as a line (or markers)
title(label) Sets the chart title
xlabel(label), ylabel(label) Label the two axes
xticks(ticks, labels), yticks(ticks, labels) Set tick positions and, optionally, the text shown at them
grid(True) Adds background grid lines
legend() Places the legend
savefig('x.png') Saves the figure as an image file
show() Displays the figure

A first line chart

Worked example: three days of temperature. Plot the maximum temperature of a city on 25, 26 and 27 December and decorate the chart.

Code
import matplotlib.pyplot as plt
date = ["25/12", "26/12", "27/12"]
temp = [8.5, 10.5, 6.8]
plt.plot(date, temp)
plt.xlabel("Date")
plt.ylabel("Temperature")
plt.title("Date wise Temperature")
plt.grid(True)
plt.yticks(temp)
plt.show()
Step Line What it does
1 plt.plot(date, temp) Draws a line through the points (25/12, 8.5), (26/12, 10.5), (27/12, 6.8). The first argument is x, the second is y
2 xlabel and ylabel Name the axes, so the viewer knows what the numbers mean
3 title Names the chart
4 grid(True) Draws background grid lines
5 yticks(temp) Puts the y tick marks exactly at the three temperatures
6 show() Opens the figure. Without it a script draws nothing on screen

The line rises from 8.5 to a peak of 10.5 on 26/12 and falls to 6.8. Without the labels and the title, the same picture would carry much less meaning.

Pause and predict: What happens if you give plt.plot() only one list, such as plt.plot(temp)?

Check your answer: Matplotlib treats the list as the y values and generates the x values itself as 0, 1, 2 and so on (the positions). It does not fail.

Customising a line: marker, colour, width and style

A marker is a symbol drawn at each data point. Pass it with marker=. Colours come from character codes or names with color=. Width and style come from linewidth= (a number, the default is 1) and linestyle= (a string).

Marker Shape
'.' Point
'o' Circle
'v' and '^' Triangle down and triangle up
'<' and '>' Triangle left and triangle right
's' Square
'p' Pentagon
'*' Star
'+' and 'x' Plus and cross
'D' Diamond
'h' and 'H' Hexagons
Colour code Colour
'b' Blue
'g' Green
'r' Red
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White
linestyle Looks like
'solid' (or '-') Continuous line, the default
'dashed' (or '--') Dashes
'dotted' (or ':') Dots
'dashdot' (or '-.') Alternating dash and dot

Worked example: turn a specification into code. Plot average height (y, in cm) against average weight (x, in kg) for ages 8 to 16, with a green dashed line of width 2, star markers of size 10, axis labels and a title.

Requirement Parameter or function
x axis is weight, y axis is height plt.plot(df.weight, df.height, …)
Green line color='green'
Star marker, size 10 marker='*', markersize=10
Dashed, width 2 linestyle='dashed', linewidth=2
Labels and title xlabel, ylabel, title
Code
import matplotlib.pyplot as plt
import pandas as pd
height = [121.9, 124.5, 129.5, 134.6, 139.7, 147.3, 152.4, 157.5, 162.6]
weight = [19.7, 21.3, 23.5, 25.9, 28.5, 32.1, 35.7, 39.6, 43.2]
df = pd.DataFrame({"height": height, "weight": weight})
plt.xlabel('Weight in kg')
plt.ylabel('Height in cm')
plt.title('Average weight with respect to average height')
plt.plot(df.weight, df.height, marker='*', markersize=10, color='green', linewidth=2, linestyle='dashed')
plt.show()

A common slip is swapping the two arguments. The first argument of plot() is always x, so plt.plot(df.height, df.weight) would put height on the horizontal axis.

Beyond the textbook. For the exam: write each property as a keyword: marker=, color=, linestyle=, linewidth=. In reality: plt.plot also accepts a compact format string. The call plt.plot(x, y, 'r*--') draws a red line with star markers and dashes in one go, and '-^' means a solid line with upward triangles. Both forms mean the same thing, and the keyword form is the safe one to use in answers.

Plotting straight from a DataFrame: df.plot()

Series and DataFrame objects have their own plot() method. It is a wrapper around pyplot's plot(), so you can mix it with pyplot decorations such as plt.title() and plt.xlabel(). The chart type is chosen with the keyword kind.

kind= Plot
'line' Line plot (the default)
'bar' Vertical bar plot
'barh' Horizontal bar plot
'hist' Histogram
'box' Box plot
'area' Area plot
'pie' Pie plot
'scatter' Scatter plot

The mela sales file MelaSales.csv has the sales of each day for three weeks, plus the name of the day.

Day Week 1 (Rs) Week 2 (Rs) Week 3 (Rs)
Monday 5000 4000 4000
Tuesday 5900 3000 5800
Wednesday 6500 5000 3500
Thursday 3500 5500 2500
Friday 4000 3000 3000
Saturday 5300 4300 5300
Sunday 7900 5900 6000

Worked example: three coloured lines. Draw the three weeks as lines in red, blue and brown, with a title and axis labels, and name the days on the x axis.

Code
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("MelaSales.csv")
df.plot(kind='line', color=['red', 'blue', 'brown'], marker="*", markersize=10, linewidth=3, linestyle="--")
plt.title('Mela Sales Report')
plt.xlabel('Days')
plt.ylabel('Sales in Rs')
ticks = df.index.tolist()
plt.xticks(ticks, df.Day)
plt.show()

Step by step: df.plot(kind='line', …) draws one line for each numeric column, and the colour list gives them red, blue and brown in order. The legend appears by default and links each colour to its column name. A line chart needs numbers on the x axis, so the plot uses the row index (0 to 6). plt.xticks(ticks, df.Day) then replaces those numbers with the day names. The first argument of xticks is the positions, the second is the text to show.

Beyond the textbook. For the exam: call plt.show() last. In reality: if you also want the picture saved, call plt.savefig('x.png') before plt.show(). Once the window is shown and closed, the figure is cleared, and saving afterwards often gives an empty file.

Bar chart: comparing categories

A line joins points and suggests a trend. When your goal is comparison between the weeks or between categories, use bars. Bar charts can also put text, such as day names, on the x axis. If you do not tell plot() which column to use for x, it uses the row index 0, 1, 2…, so name the column with x=.

Code
df.plot(kind='bar', x='Day', title='Mela Sales Report')
plt.ylabel('Sales in Rs')
plt.show()

You can also customise the bars: color=['red', 'yellow', 'purple'] gives one colour per week, edgecolor='Green' outlines each bar, and linewidth=2 and linestyle='--' style that outline. To make the bars horizontal, use kind='barh'.

Worked example: read the totals. Which day has the best total sales across the three weeks, and which week was best?

Step What we do Result
1 Add the three weeks for each day (axis=1) Mon 13000, Tue 14700, Wed 15000, Thu 11500, Fri 10000, Sat 14900, Sun 19800
2 Pick the largest Sunday, 19800
3 Add each week down the days (axis=0) Week 1: 38100, Week 2: 30700, Week 3: 30100
4 Pick the largest Week 1

On the bar chart this reads as: the Sunday group of bars is the tallest, and the Week 1 bars add up to the most.

Histogram: how often do values fall in each range?

A histogram looks like a bar chart but each column covers a range of values (a bin), and the column's height is the number of data points in that range. The bars touch each other because the ranges are continuous. df.plot(kind='hist') chooses the bins itself, or you set them with bins=: a number such as bins=20, or a list of edges such as bins=[18,19,20,21,22], or range(18,25).

Feature Bar chart Histogram
Each bar shows One category A range (bin) of numbers
Gaps between bars Yes No, the ranges are continuous
x axis Categories (text allowed) Numeric scale
Height means The value of that category How many data points fall in the bin

Worked example: counting into bins. Six heights are 60, 61, 63, 65, 61 and 60 cm. Use the bin edges 60, 62, 64 and 66. How tall is each column?

Step What we do Result
1 The bins are 60 to 62, 62 to 64, 64 to 66 Three columns
2 Each bin includes its left edge and excludes its right edge, except the last bin, which includes both 62 belongs to the second bin
3 Count: 60, 61, 61, 60 fall in the first bin 4
4 63 falls in the second bin 1
5 65 falls in the third bin 1

The heights of the three columns are 4, 1 and 1. Customising is done with keywords: edgecolor='Green' for the border, linewidth=2, linestyle=':', fill=False for empty bars and hatch='o' for a pattern. In df.plot(kind='hist') only numeric columns are drawn, so a text column such as Name is skipped.

Pause and predict: A histogram of 117 yearly minimum temperatures has a tall column in the middle and short columns at both ends. What does it tell you about the temperatures?

Check your answer: Most years had a minimum close to the middle value, and very low or very high minimums were rare. A histogram shows the frequency pattern (the distribution), which a line chart of the same values would not show so quickly.

A frequency polygon is a line drawn through the midpoints of the tops of the histogram bars. You compute the heights and bin edges with np.histogram, find each midpoint as the average of its two edges (mid = 0.5 * (edges[1:] + edges[:-1])) and draw it over the histogram with plt.plot(mid, y, '-^').

Open data portals, such as the Government of India's data.gov.in, publish large datasets that anyone can download and plot. A temperature dataset, for example, can be read with pd.read_csv(..., usecols=[...]), where usecols loads only the columns you name.

Scatter plot: is there a relationship?

A scatter plot puts one dot for every pair of values, one variable on each axis, to show whether two variables are related. That is why it is also called a correlation plot. The size, colour or shape of the dots can carry a third variable.

Worked example: discount against sales. A shop offers discounts of 10, 20, 30, 40 and 50 percent over five weeks and records the sales in rupees.

Code
import numpy as np
import matplotlib.pyplot as plt
discount = np.array([10, 20, 30, 40, 50])
saleInRs = np.array([40000, 45000, 48000, 50000, 100000])
size = discount * 10
plt.scatter(x=discount, y=saleInRs, s=size, color='red', linewidth=3, marker='*', edgecolor='blue')
plt.title('Sales Vs Discount')
plt.xlabel('Discount offered')
plt.ylabel('Sales in Rs')
plt.show()
Parameter Meaning Here
x, y The two variables Discount, sales
s Size of each marker discount * 10, so 100, 200, 300, 400, 500: a bigger discount gives a bigger star
color, marker, edgecolor, linewidth Colour, shape, outline colour and outline width Red stars with a blue outline

Reading the chart: as the discount rises, sales rise too (a positive relationship), and the jump from 40 to 50 percent doubles the sales from 50000 to 100000. Note that plt.scatter(x=…, y=…) takes arrays directly. If you use df.plot(kind='scatter') instead, you must name the DataFrame columns with x='column1', y='column2', because a DataFrame has many columns.

Box plot: the five number summary in one picture

Quartiles divide sorted data into four equal parts. The first quartile Q1 (25 percent point), the second quartile Q2 (the median, 50 percent) and the third quartile Q3 (75 percent) mark the splits. A box plot draws the summary: the box runs from Q1 to Q3 with a line at the median, the whiskers reach out to the lowest and highest ordinary values, and points beyond the whiskers are shown separately as outliers, values far from the rest.

Part of the box plot What it shows
Line inside the box Median (Q2)
Box edges Q1 and Q3, so the box holds the middle half of the data
Whiskers Lowest and highest values that are not outliers
Separate dots Outliers
Short box and short whiskers Small variation, consistent data
Long box or long whiskers Large variation, spread out data
Code
df = pd.read_csv('Marks.csv')
df.plot(kind='box')
plt.title('Performance Analysis')
plt.xlabel('Subjects')
plt.ylabel('Marks')
plt.show()

Worked example: read the box plot of 13 students in five subjects. The marks, summarised, are:

Subject Lowest Q1 Median Q3 Highest
English 60 73 80 92 95
Maths 33 43 50 63 95
Hindi 39 51 55 67 90
Science 48 52 56 76 94
Social Studies 54 71 76 80 95

Which subject has the least variation, and which shows outliers? Variation is the size of the box, $\text{IQR} = Q_3 - Q_1$. English has 19, Maths 20, Hindi 16, Science 24 and Social Studies 9. Social Studies has the smallest box, so it is the most consistent subject.

To find outliers, matplotlib uses the rule that a point is an outlier if it lies more than $1.5 \times \text{IQR}$ beyond the box. For Social Studies:

Step Calculation Result
Spread of the box $80 - 71$ $\text{IQR} = 9$
Allowed reach $1.5 \times 9$ $13.5$
Lower fence $71 - 13.5$ $57.5$
Upper fence $80 + 13.5$ $93.5$
Outliers Values below 57.5 or above 93.5 54 and 95

So Social Studies shows two outliers, 54 and 95. Applying the same rule to Maths (fences 13 and 93) gives one outlier, 95. The other subjects have none.

Beyond the textbook. For the exam: an outlier is a value numerically distant from the rest, and the whiskers reach the highest and lowest values. In reality: in matplotlib's default box plot the whiskers stop at the furthest data point within 1.5 times the IQR of the box. Anything beyond is drawn as an outlier dot, which is why "whisker reaches the highest value" is true only when no outlier exists.

For a horizontal box plot, add vert=False, and color='red' changes the colour: df.plot(kind='box', title='Compare Resorts', color='red', vert=False).

Pie chart: parts of a whole

A pie divides a circle into sectors, each sector showing a part of the total. For df.plot(kind='pie') you must choose the column with y= (or set subplots=True, which draws one pie for each numeric column). The label of each sector is, by default, the row index of the DataFrame.

Code
df = pd.DataFrame({'mass': [0.330, 4.87, 5.97], 'radius': [2439.7, 6051.8, 6378.1]}, index=['Mercury', 'Venus', 'Earth'])
df.plot(kind='pie', y='mass')
plt.show()

The sectors are labelled Mercury, Venus and Earth because they are the index values. Two keywords customise a pie. explode takes a list of fractions of the radius by which each sector is pulled out, and autopct formats the percentage printed on each sector. legend=False removes the legend, and colors sets the sector colours.

Worked example: forest cover of north eastern states. Draw a pie of forest cover with the first sector exploded by 0.1 and the fifth by 0.2, and percentages to two decimals.

Code
exp = [0.1, 0, 0, 0, 0.2, 0, 0]
c = ['r', 'g', 'm', 'c', 'brown', 'pink', 'purple']
df.plot(kind='pie', y='ForestCover', title='Forest cover of North Eastern states', legend=False, explode=exp, autopct="%.2f", colors=c)
plt.show()

With legend=False the legend box is not drawn. The percentage of each sector is its share of the total forest cover of 170423 sq km.

State Forest cover (sq km) Share printed by autopct
Arunachal Pradesh 67353 39.52
Assam 27692 16.25
Manipur 17280 10.14
Meghalaya 17321 10.16
Mizoram 19240 11.29
Nagaland 13464 7.90
Tripura 8073 4.74

As a check, take Arunachal Pradesh: $\dfrac{67353}{170423} \times 100 = 39.52$. The explode list has one number for each sector, in the same order as the rows, so the first value 0.1 pulls out Arunachal Pradesh and the fifth value 0.2 pulls out Mizoram.

Pause and predict: You run df.plot(kind='pie') on a DataFrame with two numeric columns and give no y. What happens?

Check your answer: You get an error, because Pandas does not know which column to turn into sectors. Give y='column' or subplots=True.

Exam traps

Trap Why it is tempting Truth
plt.plot(kind='bar') draws a bar chart kind= appears everywhere in this chapter kind belongs to the Pandas df.plot(). Pyplot has separate functions: plt.bar(), plt.hist() and so on
A script draws a chart without show() Notebooks display charts automatically In a normal script, plt.show() is what displays the figure
A histogram is a bar chart Both have rectangles A histogram bar covers a range of numbers, and the bars touch
Pie needs only kind='pie' Other kinds work like that It also needs y='column' (or subplots=True)
The box plot shows how many values lie in each range Both summarise data That is the histogram. The box plot shows median, quartiles and outliers
Bar chart with no x= shows the day names The Day column is in the file Without x='Day', the x axis uses the row index 0, 1, 2…
plt.xticks(labels, positions) Names sound like the other order The order is xticks(ticks, labels): positions first, text second
df.plot(kind='scatter') works without columns plt.scatter takes arrays The DataFrame version needs x='col1', y='col2'

60-second revision

Chart Best for Pyplot kind= Key keywords
Line Trend over time plot() 'line' color, marker, linestyle, linewidth
Bar Compare categories bar() 'bar', 'barh' x=, color, edgecolor
Histogram Frequency in ranges hist() 'hist' bins, edgecolor, fill, hatch
Scatter Relationship of two variables scatter() 'scatter' s, color, marker, edgecolor
Box Median, quartiles, outliers boxplot() 'box' vert=False, color
Pie Parts of a whole pie() 'pie' y, explode, autopct, colors, legend

Always add title, xlabel, ylabel (and legend for several series), then show(). Use savefig('name.png') to save.

Where this chapter connects

Chapter Link
The DataFrames being plotted Data Handling using Pandas I
Statistics such as the median, quartiles and groupby that feed the charts Data Handling using Pandas II
Where datasets come from and how they are described Understanding Data

🎯 Practice MCQs

First 3 questions free · create a free account to unlock the rest — answers & explanations included, no payment needed

Q1. In the statement import matplotlib.pyplot as plt, the name plt is

▸ Show answer & explanation

Answer: A

The keyword as creates a short name for the module, so plt.plot() means matplotlib.pyplot.plot(). Any other alias would work equally well. plt is not a function, it is not built in (Matplotlib has to be installed with pip), and it is not a file name.

Q2. Which function is used to save the current figure as an image file?

▸ Show answer & explanation

Answer: A

plt.savefig('x.png') writes the figure to a file. show() only displays it. Pyplot has no functions called save() or export() for figures.

Q3. Which kind value in df.plot() draws horizontal bars?

▸ Show answer & explanation

Answer: C

kind='barh' gives horizontal bars, while kind='bar' gives vertical ones. hbar and horizontal are not valid kind values. The vert=False keyword belongs to box plots, not bar charts.

🔒 12 more practice MCQs

Create a free account to unlock every MCQ in this chapter — answers and explanations included. No payment needed.

Already registered? Just log in and they'll all appear here.

📊 Previous-Year Questions

Practise with real CUET Computer Science previous-year papers — every question solved, with the correct answer and a step-by-step explanation.

View solved CUET PYQ papers →

Ready to drill Computer Science?

Unlock all MCQs, chapter tests, mocks & PYQs for ₹199/year.

Get UniDrill Pro