0
0
Matplotlibdata~30 mins

Custom tick formatters in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Tick Formatters with Matplotlib
📖 Scenario: You are creating a simple line chart to show daily temperatures over a week. The x-axis shows days as numbers (1 to 7), but you want to display the day names instead (like Mon, Tue, Wed, etc.).
🎯 Goal: Build a matplotlib plot with custom tick labels on the x-axis using a custom tick formatter function.
📋 What You'll Learn
Create a list of temperatures for 7 days.
Create a list of day names for the x-axis labels.
Write a custom tick formatter function to convert day numbers to day names.
Apply the custom tick formatter to the x-axis.
Display the plot with the custom labels.
💡 Why This Matters
🌍 Real World
Custom tick formatters are used in data visualization to make charts clearer and more user-friendly by showing labels that people understand easily.
💼 Career
Data scientists and analysts often customize plots to communicate insights effectively to non-technical audiences.
Progress0 / 4 steps
1
Create temperature data and day numbers
Create a list called temperatures with these exact values: [22, 21, 23, 24, 20, 19, 18]. Also create a list called days with numbers from 1 to 7.
Matplotlib
Need a hint?

Use square brackets to create lists. The days list should have numbers 1 through 7.

2
Create day names list
Create a list called day_names with these exact strings: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].
Matplotlib
Need a hint?

Use square brackets and quotes to create a list of strings.

3
Write custom tick formatter function
Import matplotlib.pyplot as plt and matplotlib.ticker as mticker. Then write a function called day_formatter that takes a parameter x and returns the day name from day_names at index int(x) - 1. Use mticker.FuncFormatter to create a formatter called formatter using day_formatter.
Matplotlib
Need a hint?

The formatter function must accept two parameters: x and pos (pos can be optional). Use int(x) - 1 to get the correct index.

4
Plot data and apply custom tick formatter
Create a plot using plt.plot(days, temperatures). Then set the x-axis major formatter to formatter using plt.gca().xaxis.set_major_formatter(formatter). Finally, display the plot with plt.show().
Matplotlib
Need a hint?

Use plt.plot() to draw the line. Use plt.gca().xaxis.set_major_formatter(formatter) to apply the custom labels. Then call plt.show() to display.