0
0
Matplotlibdata~20 mins

Why axis formatting matters in Matplotlib - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Axis Formatting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
visualization
intermediate
2:00remaining
Identify the effect of axis formatting on a plot

Look at the following code that plots a simple line chart. Which option shows the plot with the x-axis labels formatted as dates?

Matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta

dates = [datetime(2024, 1, 1) + timedelta(days=i) for i in range(5)]
values = [10, 15, 7, 12, 9]

fig, ax = plt.subplots()
ax.plot(dates, values)

# Axis formatting missing here

plt.show()
Aax.yaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
Bax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
Cax.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'{x:.2f}'))
Dax.xaxis.set_major_locator(plt.MaxNLocator(integer=True))
Attempts:
2 left
💡 Hint

Think about which axis shows dates and how to format them properly.

Predict Output
intermediate
1:30remaining
What is the output of this axis formatting code?

What will be the output of the following code snippet?

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.arange(5), np.arange(5)**2)
ax.set_xticks([0, 1, 2, 3, 4])
ax.set_xticklabels(['zero', 'one', 'two', 'three', 'four'])
labels = [label.get_text() for label in ax.get_xticklabels()]
print(labels)
A['zero', 'one', 'two', 'three', 'four']
B['0', '1', '2', '3', '4']
C['zero', 'one', 'two', 'three', 'four', '']
D['zero', 'one', 'two', 'three']
Attempts:
2 left
💡 Hint

Check how many labels are set and what get_xticklabels() returns.

data_output
advanced
1:30remaining
How many ticks are shown after axis formatting?

Given this code, how many ticks will be visible on the y-axis?

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.arange(10), np.random.rand(10))
ax.yaxis.set_major_locator(plt.MaxNLocator(4))
ticks = ax.get_yticks()
print(len(ticks))
A5
B10
CCannot determine without plotting
D4
Attempts:
2 left
💡 Hint

Remember that MaxNLocator(4) tries to show up to 4 intervals, which means 5 ticks.

🔧 Debug
advanced
2:00remaining
Why does this axis formatting code raise an error?

Consider this code snippet:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.xaxis.set_major_formatter('%Y-%m-%d')
plt.show()

Why does it raise an error?

ABecause plt.show() is missing parentheses
BBecause the plot data is not dates
CBecause set_major_formatter expects a Formatter object, not a string
DBecause the x-axis has no ticks
Attempts:
2 left
💡 Hint

Check the type of argument set_major_formatter requires.

🚀 Application
expert
2:30remaining
Choose the correct axis formatting to display large numbers in millions

You have a plot with y-axis values in the millions (e.g., 1,000,000). Which axis formatter will display the y-axis labels as '1M', '2M', etc.?

Matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1000000, 2000000, 3000000])

# Apply correct formatter here

plt.show()
Aax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))
Bax.yaxis.set_major_formatter(ticker.PercentFormatter())
Cax.yaxis.set_major_formatter(ticker.ScalarFormatter())
Dax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, _: f'{int(x/1e6)}M'))
Attempts:
2 left
💡 Hint

Think about how to convert large numbers to a shorter string with 'M' suffix.