Informatics Practices III: Plotting Data with Matplotlib

Unit 4 of Section B2 is plotting data with Matplotlib. The syllabus names the purpose of plotting, seven kinds of plot (line, bar graph, histogram, pie chart, frequency polygon, box plot and scatter plot), drawing and saving them, and customising colour, line style, width, labels, title and legend. The skill examined is choosing the right plot for the data and reading the calls of pyplot correctly.
Overview

1. Why We Plot, and the Basic Calls

1 min read · 2 parts

A plot turns numbers into a picture so that trends, comparisons, distributions, shares and relationships can be seen at a glance, which is the purpose of plotting. With import matplotlib.pyplot as plt, the basic steps are: call a plotting function, add labels with plt.xlabel(), plt.ylabel() and plt.title(), add plt.legend() if there are several series (each labelled with label="..."), save with plt.savefig("name.png") and show with plt.show(). savefig should be called before show, because show clears the figure in many set-ups.

Customising a plot
AimArgumentExamples
Colourcolor or c"red", "g", "#1f77b4"
Line stylelinestyle or ls"-" solid, "--" dashed, ":" dotted, "-." dash-dot
Widthlinewidth or lwlw=2
Markermarker"o" circle, "s" square, "^" triangle, "*" star
Title and labelsplt.title, plt.xlabel, plt.ylabelplt.title("Sales")
Legendlabel= in each call, then plt.legend()plt.legend(loc="upper left")
The basic steps of a plot
  1. import matplotlib.pyplot as plt
  2. Call a plotting function
  3. plt.xlabel(), plt.ylabel(), plt.title()
  4. plt.legend() for several seriesEach call needs label="..."
  5. plt.savefig("name.png")Before show
  6. plt.show()

A plot turns numbers into a picture so that trends, comparisons, distributions, shares and relationships can be seen at a glance, which is the purpose of plotting. With import…

2. Choosing the Plot

2 min read · 4 parts
The seven plots in the syllabus
PlotCallUse it for
Line plotplt.plot(x, y)Change over time, such as temperature by month
Bar graphplt.bar(x, h) or plt.barhComparing separate categories; bars are separated and categories are not continuous
Histogramplt.hist(data, bins=...)Distribution of one continuous variable in class intervals; bars touch
Pie chartplt.pie(values, labels=..., autopct="%1.1f%%")Shares of a whole that add to 100 per cent
Frequency polygonplt.hist(..., histtype="step") or plt.plot of class mid-points against frequenciesShape of a distribution; compares two distributions on one graph
Box plotplt.boxplot(data)Median, quartiles and outliers of a variable, or comparison between groups
Scatter plotplt.scatter(x, y)Relationship (correlation) between two numerical variables

A bar graph and a histogram look alike but differ: a bar graph has gaps and compares categories (class sections A, B, C); a histogram has touching bars and shows how a measured variable is spread across bins (marks in 0-10, 10-20 and so on). The area of a pie slice is proportional to its value, so a pie needs positive values. In a box plot the box spans the first to third quartile, a line inside marks the median, the "whiskers" show the range of ordinary values and points beyond them are outliers. A scatter plot with points rising from left to right shows positive correlation.

⚠️ A histogram is not a bar graph
Use plt.bar for categories such as cities and plt.hist for raw measurements such as heights. Giving plt.hist already-counted frequencies produces a meaningless histogram, because hist does the counting itself.
🎯 Reading a call
plt.plot([1, 2, 3], [2, 4, 6], "r--", lw=2, label="double") draws a red (r) dashed (--) line of width 2 through (1, 2), (2, 4) and (3, 6). plt.legend() is needed or the label is never shown.
Bar graph versus histogram
Bar graph: plt.bar
  • Bars have gaps
  • Compares categories
  • Class sections A, B, C
Histogram: plt.hist
  • Bars touch
  • Spread of a measured variable in bins
  • Marks in 0-10, 10-20

A bar graph and a histogram look alike but differ: a bar graph has gaps and compares categories (class sections A, B, C); a histogram has touching bars and shows how a measured variable is…

3. The Parts of a Figure and How to Set Them

1 min read · 1 part

A complete figure has more than the data. After the plotting call, the usual calls add a title with plt.title("..."), axis labels with plt.xlabel("...") and plt.ylabel("..."), a legend with plt.legend(), which needs each plot call to have carried a label argument, and a background grid with plt.grid(True). The size of the figure is set with plt.figure(figsize=(8, 4)), in inches as width and height, before the plotting call. The figure is saved to a file with plt.savefig("chart.png") and shown on the screen with plt.show(); saving before showing is the safe order because showing can clear the figure in some setups.

Calls that decorate a plot
CallEffectNeeds
plt.title("T")Adds a headingText
plt.xlabel / ylabelNames the axesText
plt.legend()Shows a keylabel= in each plot call
plt.grid(True)Draws grid linesNothing
plt.savefig("f.png")Writes a fileFile name

A complete figure has more than the data. After the plotting call, the usual calls add a title with plt.title("..."), axis labels with plt.xlabel("...") and plt.ylabel("..."), a legend with…

4. Reading and Writing Plot Calls

1 min read · 1 part

Two skills decide most questions in this chapter. The first is reading a call: in plt.bar(["A", "B", "C"], [30, 45, 25], color="green") the first list gives the category labels on the x-axis and the second the heights of the three bars, so B is the tallest at 45. The second is choosing the plot from the situation. A company's sales over twelve months need a line plot, because order and trend matter. Marks of 40 students grouped into ranges need a histogram, which bins continuous values, while the number of students in each of four houses needs a bar chart, which compares categories. The share of four expense heads in a budget suits a pie chart, which shows parts of a whole and so must add up to a whole, and the link between hours studied and marks is a scatter plot of paired values.

⚠️ Pie and histogram traps
A pie chart cannot show change over time, and a histogram needs numerical data to bin, not named categories. If the question gives cities and populations, the answer is a bar chart; if it gives raw heights of students, it is a histogram. For a pie chart the call is plt.pie(values, labels=names, autopct="%1.1f%%"), where autopct prints each share as a percentage.

Two skills decide most questions in this chapter. The first is reading a call: in plt.bar(["A", "B", "C"], [30, 45, 25], color="green") the first list gives the category labels on the…

Subplots and Multiple Series

1 min read

Two or more datasets can share one set of axes. Calling plt.plot twice, each with its own label, draws two lines on the same graph, and plt.legend() then tells them apart. For bar charts of two groups side by side, the x positions of the second group are shifted by the bar width so that the bars do not overlap. When the datasets deserve separate panels, plt.subplot(rows, cols, index) divides the figure into a grid and selects a panel, with the index counting from 1 across the rows, so plt.subplot(1, 2, 2) is the right-hand panel of a one-row, two-column layout. Each panel has its own title and labels, and plt.tight_layout() adjusts spacing so that labels do not collide. Questions usually ask what a given set of calls produces, so count the plot calls and check the grid.

Two or more datasets can share one set of axes. Calling plt.plot twice, each with its own label, draws two lines on the same graph, and plt.legend() then tells them apart. For bar charts of…

Common Errors in Plot Calls

1 min read

Most plotting questions that go wrong do so for the same few reasons. The x list and the y list given to plt.plot must have the same length, or Matplotlib raises an error. Calling plt.legend() without a label argument in the plot calls draws an empty legend. Forgetting plt.show() means nothing appears in a plain script. Using plt.hist on category names fails, because a histogram needs numbers. And placing plt.savefig after plt.show() can save a blank figure in some setups, so save first. A quick check of lengths, labels and the order of calls catches most of these before the code is run.

Most plotting questions that go wrong do so for the same few reasons. The x list and the y list given to plt.plot must have the same length, or Matplotlib raises an error. Calling…

Key takeaways

  • Plots turn data into pictures to show trends, comparisons, distributions, shares and relationships.
  • Use plt.plot for trends, bar for categories, hist for distributions, pie for shares, boxplot for quartiles and outliers, and scatter for relationships.
  • Customise with color, linestyle, linewidth and marker; add xlabel, ylabel, title and label with legend; call savefig before show.
  • A bar graph has gaps and compares categories; a histogram has touching bars and groups continuous data into bins.
  • A frequency polygon joins the mid-points of the class frequencies and a box plot shows the median, quartiles and outliers.

Practice questions (25)

Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.

  1. Which plot is best for showing how the temperature of a city changes over the twelve months?

    1. a pie chart
    2. a line plot
    3. a box plot of one value
    4. a scatter plot of month names
    Show answer

    Answer: B — a line plot

    A line plot joins points in order and so shows a trend over time. A pie chart shows shares of a whole, which temperature is not.
  2. The function to draw a histogram in Matplotlib is

    1. plt.hist()
    2. plt.bar()
    3. plt.pie()
    4. plt.scatter()
    Show answer

    Answer: A — plt.hist()

    plt.hist(data, bins=...) counts the values into class intervals itself. plt.bar draws bars from given heights.
  3. Which plot shows the relationship between two numerical variables, such as height and weight?

    1. pie chart
    2. bar graph of categories
    3. frequency polygon only
    4. scatter plot
    Show answer

    Answer: D — scatter plot

    Each point is one person with an x and a y value, so the pattern of points shows correlation. A pie chart cannot show two variables.
Show the other 22 questions
  1. In a box plot, the line inside the box marks the

    1. mean
    2. maximum
    3. median
    4. mode
    Show answer

    Answer: C — median

    The box runs from the first to the third quartile and the middle line is the median. Points beyond the whiskers are outliers.
  2. What does plt.plot(x, y, "g:", lw=3) draw?

    1. a green dashed line of width 3
    2. a green dotted line of width 3
    3. a red dotted line
    4. three green points
    Show answer

    Answer: B — a green dotted line of width 3

    g stands for green, ":" for a dotted style and lw for line width. A dashed line would be "--".
  3. To display the labels given to several lines with label="...", the code must also call

    1. plt.legend()
    2. plt.title()
    3. plt.grid()
    4. plt.axis()
    Show answer

    Answer: A — plt.legend()

    The label argument only names a series; plt.legend() draws the key. plt.title sets the heading of the whole plot.
  4. A bar graph differs from a histogram because a bar graph

    1. groups continuous data into touching bins
    2. always shows percentages
    3. needs no labels
    4. compares separate categories with gaps between bars
    Show answer

    Answer: D — compares separate categories with gaps between bars

    Categories such as classes or cities have no natural order of continuity, so bars are separated; a histogram's bins form a continuous scale.
  5. The autopct argument of plt.pie() is used to

    1. set the colours
    2. rotate the figure
    3. print the percentage on each slice
    4. save the file
    Show answer

    Answer: C — print the percentage on each slice

    A format such as "%1.1f%%" shows each share to one decimal place. Colours are set with colors=.
  6. A frequency polygon is drawn by joining

    1. the upper limits of classes with a pie
    2. the mid-points of the class intervals plotted against their frequencies
    3. random points
    4. only the highest bar
    Show answer

    Answer: B — the mid-points of the class intervals plotted against their frequencies

    It is the line version of a histogram and lets two distributions be compared on one set of axes.
  7. To keep a copy of a plot as an image file, which call is used, and when?

    1. plt.savefig("plot.png"), before plt.show()
    2. plt.save(), after plt.show()
    3. plt.print(), anywhere
    4. plt.export(), before the import
    Show answer

    Answer: A — plt.savefig("plot.png"), before plt.show()

    show can clear the figure, so saving afterwards may write a blank file. The function is savefig, and a name with .png, .jpg or .pdf sets the format.
  8. Which Matplotlib function is used to label the x-axis?

    1. plt.xlabel()
    2. plt.title()
    3. plt.legend()
    4. plt.grid()
    Show answer

    Answer: A — plt.xlabel()

    plt.xlabel sets the label of the x-axis. plt.title sets the heading of the whole plot.
  9. The function that displays the figure on the screen is:

    1. plt.show()
    2. plt.savefig()
    3. plt.plot()
    4. plt.legend()
    Show answer

    Answer: A — plt.show()

    plt.show() displays the figure. plt.savefig() writes it to a file and plt.plot() only draws.
  10. Which chart is best for comparing the sales of five products?

    1. Bar chart
    2. Histogram
    3. Box plot
    4. Line chart over time
    Show answer

    Answer: A — Bar chart

    A bar chart compares values across separate categories. A histogram shows the distribution of one continuous variable.
  11. The function plt.title("Sales") is used to:

    1. Give the plot a heading
    2. Name the x-axis
    3. Save the plot
    4. Draw a line
    Show answer

    Answer: A — Give the plot a heading

    plt.title adds a heading above the plot. Naming an axis is done with xlabel or ylabel.
  12. The statement plt.plot(x, y, "r--") draws:

    1. A red dashed line
    2. A red solid line with circles
    3. A green dotted line
    4. A red bar
    Show answer

    Answer: A — A red dashed line

    The code r means red and -- means a dashed line. A green dotted line would be "g:".
  13. Match List I with List II:
    List I:
    A. plt.xlabel();
    B. plt.title();
    C. plt.legend();
    D. plt.savefig()
    List II:
    1. Shows labels of the plotted lines;
    2. Saves the figure as a file;
    3. Names the x-axis;
    4. Adds a heading to the plot

    1. A-3, B-4, C-1, D-2
    2. A-4, B-3, C-1, D-2
    3. A-3, B-4, C-2, D-1
    4. A-3, B-1, C-4, D-2
    Show answer

    Answer: A — A-3, B-4, C-1, D-2

    xlabel names the axis (3), title adds a heading (4), legend shows labels (1) and savefig writes a file (2). Option 2 swaps xlabel and title.
  14. A pie chart is most suitable for showing:

    1. The share of each part in a whole
    2. The change of a value over time
    3. The relation between two numeric variables
    4. The median and quartiles
    Show answer

    Answer: A — The share of each part in a whole

    A pie divides a whole into slices. Change over time suits a line chart and a relation suits a scatter plot.
  15. In plt.bar(x, y, width=0.5), the argument width controls:

    1. The thickness of each bar
    2. The colour of the bars
    3. The number of bars
    4. The title of the chart
    Show answer

    Answer: A — The thickness of each bar

    width sets how wide each bar is. Colour is set with the color argument.
  16. Assertion (A): A scatter plot is used to study the relationship between two numeric variables.
    Reason (R): Each point shows the pair of values for one observation, so patterns such as a rising trend become visible.
    Choose the correct option:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    Show answer

    Answer: A — Both A and R are true and R is the correct explanation of A

    Points for pairs reveal patterns between the variables, as R states. Option 2 is wrong.
  17. Consider the following statements:
    A. plt.legend() needs the label argument given in the plot calls to show names.
    B. plt.hist() has a bins argument.
    C. plt.show() saves the figure as a file.
    D. plt.xlim() sets the limits of the x-axis.
    Choose the correct answer:

    1. A, B and D only
    2. A and C only
    3. B, C and D only
    4. A, B, C and D
    Show answer

    Answer: A — A, B and D only

    A, B and D are correct. C is false because savefig saves the figure while show only displays it, so option 4 is the trap.
  18. plt.plot([3, 5, 7]) is called with only one list. What does it plot?

    1. The values 3, 5, 7 against the x-positions 0, 1, 2
    2. The values against 3, 5, 7 on the x-axis
    3. Only three separate points with no x-values
    4. An error is raised
    Show answer

    Answer: A — The values 3, 5, 7 against the x-positions 0, 1, 2

    With a single list Matplotlib uses the indices 0, 1, 2 as the x-values. No error is raised.
  19. Assertion (A): Increasing the number of bins in a histogram shows finer detail of the distribution.
    Reason (R): Each bin then counts the values in a smaller interval.
    Choose the correct option:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    Show answer

    Answer: A — Both A and R are true and R is the correct explanation of A

    Narrower intervals reveal more detail, which R states. Option 2 is wrong.
  20. The function plt.barh() draws:

    1. Horizontal bars
    2. Vertical bars only
    3. A pie chart
    4. A histogram
    Show answer

    Answer: A — Horizontal bars

    barh draws horizontal bars, whereas bar draws vertical ones. It is not a pie chart or a histogram.
  21. To show two data series with different colours in one plot and identify them, the correct sequence is:

    1. plt.plot() twice with label arguments, then plt.legend()
    2. plt.legend() first and plt.plot() later without labels
    3. plt.savefig() only
    4. plt.bar() only
    Show answer

    Answer: A — plt.plot() twice with label arguments, then plt.legend()

    The labels given while plotting are what legend() displays. Calling legend() first or without labels shows nothing useful.
  22. A line chart rather than a bar chart is better for data such as the daily closing price of a share over a month because:

    1. It shows the trend over a continuous sequence of time clearly
    2. It compares unrelated categories
    3. It shows the median only
    4. It shows shares of a whole
    Show answer

    Answer: A — It shows the trend over a continuous sequence of time clearly

    Lines connect successive points and so reveal trends over time. Bars suit separate categories and pies suit shares of a whole.