Bird
Raised Fist0
Matplotlibdata~20 mins

Custom tick formatters in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using a FuncFormatter in matplotlib?
easy
A. To change the color of the plot lines
B. To customize how tick labels are displayed on an axis
C. To add grid lines to the plot
D. To set the plot title

Solution

  1. Step 1: Understand what tick labels are

    Tick labels are the numbers or text shown on the axis to indicate scale or categories.
  2. Step 2: Role of FuncFormatter

    FuncFormatter lets you define a function that changes how these labels appear, for example formatting numbers or adding units.
  3. Final Answer:

    To customize how tick labels are displayed on an axis -> Option B
  4. Quick Check:

    FuncFormatter changes tick labels [OK]
Hint: FuncFormatter changes axis label text format fast [OK]
Common Mistakes:
  • Confusing FuncFormatter with plot styling functions
  • Thinking it changes plot colors
  • Assuming it adds grid lines
2. Which of the following is the correct way to import FuncFormatter from matplotlib?
easy
A. from matplotlib.ticker import FuncFormatter
B. import matplotlib.pyplot as FuncFormatter
C. from matplotlib import FuncFormatter
D. import FuncFormatter from matplotlib.ticker

Solution

  1. Step 1: Identify the module for FuncFormatter

    FuncFormatter is part of the ticker module in matplotlib, so it must be imported from matplotlib.ticker.
  2. Step 2: Check correct Python import syntax

    The correct syntax is 'from matplotlib.ticker import FuncFormatter'. Other options either use wrong syntax or wrong module.
  3. Final Answer:

    from matplotlib.ticker import FuncFormatter -> Option A
  4. Quick Check:

    Correct import = from matplotlib.ticker import FuncFormatter [OK]
Hint: FuncFormatter is in matplotlib.ticker module [OK]
Common Mistakes:
  • Using wrong import syntax
  • Importing from matplotlib.pyplot
  • Trying to import directly from matplotlib
3. What will be the output tick labels on the x-axis after running this code?
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

def format_func(value, tick_number):
    return f"${value:.1f}k"

fig, ax = plt.subplots()
ax.plot([1000, 2000, 3000])
ax.xaxis.set_major_formatter(FuncFormatter(format_func))
plt.show()
medium
A. Tick labels like '1000', '2000', '3000'
B. Tick labels like '0', '1', '2'
C. Tick labels like '$0.0k', '$1.0k', '$2.0k'
D. Tick labels like 'k0.0$', 'k1.0$', 'k2.0$'

Solution

  1. Step 1: Understand the formatter function

    The function formats the tick value as a string with a dollar sign, one decimal place, and 'k' suffix, e.g. '$0.0k'.
  2. Step 2: Check the x-axis tick values

    Since the plot has 3 points, the default ticks are at positions 0, 1, 2. The formatter converts these to '$0.0k', '$1.0k', '$2.0k'.
  3. Final Answer:

    Tick labels like '$0.0k', '$1.0k', '$2.0k' -> Option C
  4. Quick Check:

    Formatter adds $ and k to tick numbers [OK]
Hint: Formatter changes tick numbers to strings with $ and k [OK]
Common Mistakes:
  • Assuming formatter changes data points instead of ticks
  • Expecting original data values as labels
  • Confusing tick positions with data values
4. Identify the error in this code snippet that tries to format y-axis ticks with percentages:
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

def percent(x, pos):
    return f"{x}%"

fig, ax = plt.subplots()
ax.plot([0.1, 0.2, 0.3])
ax.yaxis.set_major_formatter(FuncFormatter(percent))
plt.show()
medium
A. The percent function should multiply by 100 and add % sign as string
B. The percent function should return a string with % sign, but it returns a float
C. The percent function is missing the pos parameter
D. The FuncFormatter is applied to xaxis instead of yaxis

Solution

  1. Step 1: Examine the percent function

    The function returns f"{x}%", e.g., for x=0.1 it returns "0.1%", which does not properly represent a percentage.
  2. Step 2: Identify the required change

    For percentage formatting, the function should multiply x by 100 before appending the % sign, e.g., "10%" for 0.1.
  3. Final Answer:

    The percent function should multiply by 100 and add % sign as string -> Option A
  4. Quick Check:

    Percent formatters multiply by 100 [OK]
Hint: Formatter functions must return strings, not numbers [OK]
Common Mistakes:
  • Returning numbers instead of strings from formatter
  • Forgetting to multiply by 100 for percentages
  • Missing required function parameters
5. You want to display x-axis ticks as dates in 'Month-Day' format using a custom formatter. Which approach correctly applies this using FuncFormatter?
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import datetime

dates = [datetime.date(2024, 6, d) for d in range(1, 6)]
values = [10, 20, 15, 25, 30]

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

# Which formatter function and application is correct?
hard
A. def format_date(x, pos): return dates[int(x)].strftime('%m-%d') ax.xaxis.set_major_formatter(FuncFormatter(format_date))
B. def format_date(x, pos): return str(x) ax.xaxis.set_major_formatter(FuncFormatter(format_date))
C. def format_date(x, pos): return x.strftime('%m-%d') ax.xaxis.set_major_formatter(FuncFormatter(format_date))
D. def format_date(x, pos): return datetime.datetime.fromordinal(int(x)).strftime('%m-%d') ax.xaxis.set_major_formatter(FuncFormatter(format_date))

Solution

  1. Step 1: Understand x values in date plots

    Matplotlib converts dates to float numbers representing days since a fixed date (ordinal). So x is a float ordinal number.
  2. Step 2: Convert ordinal to date string

    Use datetime.datetime.fromordinal(int(x)) to convert float x to a date object, then format with strftime('%m-%d').
  3. Step 3: Check options

    def format_date(x, pos): return datetime.datetime.fromordinal(int(x)).strftime('%m-%d') ax.xaxis.set_major_formatter(FuncFormatter(format_date)) correctly converts x to date and formats it. def format_date(x, pos): return dates[int(x)].strftime('%m-%d') ax.xaxis.set_major_formatter(FuncFormatter(format_date)) incorrectly indexes dates list by int(x) which may cause index errors. def format_date(x, pos): return x.strftime('%m-%d') ax.xaxis.set_major_formatter(FuncFormatter(format_date)) tries to call strftime on float x, causing error. def format_date(x, pos): return str(x) ax.xaxis.set_major_formatter(FuncFormatter(format_date)) returns string of float, not formatted date.
  4. Final Answer:

    def format_date(x, pos): return datetime.datetime.fromordinal(int(x)).strftime('%m-%d') ax.xaxis.set_major_formatter(FuncFormatter(format_date)) -> Option D
  5. Quick Check:

    Date ticks need ordinal to date conversion [OK]
Hint: Convert float ticks to dates with fromordinal before formatting [OK]
Common Mistakes:
  • Using tick value as list index causing errors
  • Calling date methods on float values
  • Returning raw float strings instead of formatted dates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard