Informatics Practices III: Plotting Data with Matplotlib
2. Choosing the Plot
| Plot | Call | Use it for |
|---|---|---|
| Line plot | plt.plot(x, y) | Change over time, such as temperature by month |
| Bar graph | plt.bar(x, h) or plt.barh | Comparing separate categories; bars are separated and categories are not continuous |
| Histogram | plt.hist(data, bins=...) | Distribution of one continuous variable in class intervals; bars touch |
| Pie chart | plt.pie(values, labels=..., autopct="%1.1f%%") | Shares of a whole that add to 100 per cent |
| Frequency polygon | plt.hist(..., histtype="step") or plt.plot of class mid-points against frequencies | Shape of a distribution; compares two distributions on one graph |
| Box plot | plt.boxplot(data) | Median, quartiles and outliers of a variable, or comparison between groups |
| Scatter plot | plt.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.
- Bars have gaps
- Compares categories
- Class sections A, B, C
- 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
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.
| Call | Effect | Needs |
|---|---|---|
| plt.title("T") | Adds a heading | Text |
| plt.xlabel / ylabel | Names the axes | Text |
| plt.legend() | Shows a key | label= in each plot call |
| plt.grid(True) | Draws grid lines | Nothing |
| plt.savefig("f.png") | Writes a file | File 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
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.
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
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
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.
Which plot is best for showing how the temperature of a city changes over the twelve months?
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.The function to draw a histogram in Matplotlib is
Show answer
Answer: A — plt.hist()
plt.hist(data, bins=...) counts the values into class intervals itself. plt.bar draws bars from given heights.Which plot shows the relationship between two numerical variables, such as height and weight?
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
In a box plot, the line inside the box marks the
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.What does plt.plot(x, y, "g:", lw=3) draw?
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 "--".To display the labels given to several lines with label="...", the code must also call
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.A bar graph differs from a histogram because a bar graph
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.The autopct argument of plt.pie() is used to
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=.A frequency polygon is drawn by joining
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.To keep a copy of a plot as an image file, which call is used, and when?
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.Which Matplotlib function is used to label the x-axis?
Show answer
Answer: A — plt.xlabel()
plt.xlabel sets the label of the x-axis. plt.title sets the heading of the whole plot.The function that displays the figure on the screen is:
Show answer
Answer: A — plt.show()
plt.show() displays the figure. plt.savefig() writes it to a file and plt.plot() only draws.Which chart is best for comparing the sales of five products?
Show answer
Answer: A — Bar chart
A bar chart compares values across separate categories. A histogram shows the distribution of one continuous variable.The function plt.title("Sales") is used to:
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.The statement plt.plot(x, y, "r--") draws:
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:".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 plotShow 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.A pie chart is most suitable for showing:
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.In plt.bar(x, y, width=0.5), the argument width controls:
Show answer
Answer: A — The thickness of each bar
width sets how wide each bar is. Colour is set with the color argument.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: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.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: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.plt.plot([3, 5, 7]) is called with only one list. What does it plot?
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.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: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.The function plt.barh() draws:
Show answer
Answer: A — Horizontal bars
barh draws horizontal bars, whereas bar draws vertical ones. It is not a pie chart or a histogram.To show two data series with different colours in one plot and identify them, the correct sequence is:
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.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:
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.