Matplotlib Chart Types · Exercises
Data

Matplotlib Chart Types Exercises

4 exercises that build on the Matplotlib Chart Types lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: Each Matplotlib chart type answers a different question, so you choose the chart from the question you are asking: a histogram for spread, a scatter plot for two numbers, bars for categories, a box plot for groups and a heatmap for a grid of values. By the end you can pick the right chart for a question and draw histograms, scatter plots with trend lines, sorted, stacked and grouped bars, box plots, annotated heatmaps, and charts with reference lines or a second axis. You will practise: Draw the exam histogram; Predict the stacked bars; Fix the heatmap labels; Scatter plot with a trend line.

0 / 4 completed

Matplotlib Chart Types practice exercises

1. Draw the exam histogram

Write code Easy

scores holds the marks of 20 students. Create fig, ax = plt.subplots() and draw a histogram of scores with ax.hist() using the bins [0, 50, 60, 70, 80, 90, 100]. Keep what ax.hist() returns in the variables counts, edges, bars. Set the title to Exam scores, the x-axis label to Mark and the y-axis label to Students, then call plt.show().

Your code
import matplotlib.pyplot as plt

scores = [45, 52, 58, 61, 63, 67, 68, 70, 72, 74, 75, 77, 79, 81, 83, 85, 88, 91, 94, 97]

# draw the histogram here

2. Predict the stacked bars

Predict the output Medium

Read the code and type exactly what it prints (ignore the image). Remember that every ax.bar() call adds one bar per category, and that bottom= says where a bar starts. Then press Check.

Read this code
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
day = ax.bar(["Mon", "Tue"], [3, 5], label="day shift")
night = ax.bar(["Mon", "Tue"], [2, 4], bottom=[3, 5], label="night shift")
print(len(ax.patches))
print([float(bar.get_height()) for bar in night])
print([float(bar.get_y() + bar.get_height()) for bar in night])
print(len(ax.containers))
plt.show()

3. Fix the heatmap labels

Fix the bug Medium

The numbers written on this heatmap are in the wrong cells: the label for the cell in row 0, column 2 is not drawn on that cell (some labels even fall outside the picture). Fix the loop so that every label is written in the cell that holds its value.

Your code
import numpy as np
import matplotlib.pyplot as plt

grid = np.array([[1, 2, 3],
                 [4, 5, 6]])

fig, ax = plt.subplots()
ax.imshow(grid, cmap="Blues")
for row in range(grid.shape[0]):
    for col in range(grid.shape[1]):
        ax.text(row, col, grid[row, col], ha="center", va="center")
plt.show()

4. Scatter plot with a trend line

Write code Hard

Write a function plot_trend(x, y) that:

  1. creates fig, ax = plt.subplots(),
  2. draws the points with ax.scatter() and label="data",
  3. fits a straight line with np.polyfit(x, y, 1) and draws it over the x values with ax.plot() and label="trend",
  4. sets the title Trend line and shows a legend,
  5. returns fig, ax, slope.

The given code calls it and prints the slope. The checks call your function with other data too.

Your code
import numpy as np
import matplotlib.pyplot as plt

hours = [1, 2, 3, 4, 5, 6]
scores = [50, 55, 61, 64, 70, 75]

def plot_trend(x, y):
    # scatter the points, draw the trend line, return fig, ax, slope
    pass

fig, ax, slope = plot_trend(hours, scores)
print("Each extra hour adds about", round(slope, 1), "points")
plt.show()

Next lessonPython Calculator Project

More Matplotlib Chart Types examples · All Python exercises