0
0
Matplotlibdata~20 mins

Custom tick formatters in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Custom Tick Formatter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a custom tick formatter using FuncFormatter

What is the output of the following code snippet that uses FuncFormatter to format y-axis ticks as percentages?

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

fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0.1, 0.5, 0.9])

formatter = FuncFormatter(lambda x, _: f'{x*100:.0f}%')
ax.yaxis.set_major_formatter(formatter)

ticks = [tick.get_text() for tick in ax.yaxis.get_major_ticks()]
print(ticks)
A['0.1', '0.3', '0.5', '0.7', '0.9']
B['0%', '20%', '40%', '60%', '80%', '100%']
C['10%', '50%', '90%']
D['0', '0.2', '0.4', '0.6', '0.8', '1.0']
Attempts:
2 left
💡 Hint

Think about how the formatter multiplies the tick value by 100 and formats it as a percentage with no decimals.

data_output
intermediate
2:00remaining
Number of ticks after setting a custom formatter

After applying a custom tick formatter that formats x-axis ticks as integers with a prefix 'Val-', how many major ticks will be shown on the x-axis for the following plot?

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

fig, ax = plt.subplots()
ax.plot(range(10), range(10))

formatter = FuncFormatter(lambda x, _: f'Val-{int(x)}')
ax.xaxis.set_major_formatter(formatter)

num_ticks = len(ax.get_xticks())
print(num_ticks)
A9
B10
C12
D11
Attempts:
2 left
💡 Hint

Consider the default ticks matplotlib generates for the range 0 to 9.

🔧 Debug
advanced
2:00remaining
Identify the error in custom tick formatter code

What error will the following code raise when setting a custom tick formatter?

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

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])

def formatter(x):
    return f'Value: {x:.1f}'

ax.yaxis.set_major_formatter(FuncFormatter(formatter))
ATypeError: formatter() takes 1 positional argument but 2 were given
BNo error, runs correctly
CValueError: unsupported format string passed to float.__format__
DSyntaxError: invalid syntax in formatter function
Attempts:
2 left
💡 Hint

Check the expected signature of the function passed to FuncFormatter.

visualization
advanced
2:00remaining
Effect of a custom log scale tick formatter

Given the code below, what will the y-axis tick labels look like?

Matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.logspace(0.1, 2, 10))

formatter = FuncFormatter(lambda y, _: f'{y:.1e}')
ax.set_yscale('log')
ax.yaxis.set_major_formatter(formatter)

labels = [tick.get_text() for tick in ax.yaxis.get_major_ticks()]
print(labels)
A['1.0e+00', '1.0e+01', '1.0e+02']
B['0.1', '1.0', '10.0', '100.0']
C['0.1e+00', '1.0e+00', '10.0e+00']
D['1', '10', '100']
Attempts:
2 left
💡 Hint

Remember that the formatter formats the tick values in scientific notation with one decimal place.

🚀 Application
expert
3:00remaining
Creating a custom tick formatter for time in seconds to MM:SS format

You want to display x-axis ticks representing time in seconds as MM:SS format (minutes and seconds). Which of the following FuncFormatter functions will correctly format the ticks?

Alambda x: f'{int(x//60)}:{int(x%60)}'
Blambda x, pos: f'{x//60}:{x%60}'
Clambda x, _: f'{int(x//60):02d}:{int(x%60):02d}'
Dlambda x, _: f'{round(x/60)}:{round(x%60)}'
Attempts:
2 left
💡 Hint

Remember the formatter function must accept two arguments and format minutes and seconds with leading zeros.