Look at the following code that plots a simple line chart. Which option shows the plot with the x-axis labels formatted as dates?
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()
Think about which axis shows dates and how to format them properly.
Option B correctly formats the x-axis labels as dates using mdates.DateFormatter. Option B formats numbers with decimals, not dates. Option B tries to format the y-axis as dates, which is incorrect. Option B changes tick locations but does not format dates.
What will be the output of the following code snippet?
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)
Check how many labels are set and what get_xticklabels() returns.
The code sets 5 custom labels for the x-axis ticks. The get_xticklabels() method returns all labels including the empty last one by default, but since we set exactly 5 labels, the printed list matches those labels exactly.
Given this code, how many ticks will be visible on the y-axis?
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))
Remember that MaxNLocator(4) tries to show up to 4 intervals, which means 5 ticks.
The MaxNLocator(4) sets a maximum of 4 intervals between ticks, so the number of ticks is intervals + 1, which is 5.
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?
Check the type of argument set_major_formatter requires.
The method set_major_formatter requires a Formatter object like DateFormatter, not a plain string. Passing a string causes a TypeError.
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.?
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()
Think about how to convert large numbers to a shorter string with 'M' suffix.
Option D uses a custom function to divide the number by 1 million and add 'M' suffix, which correctly formats large numbers. Option D formats as percentages, which is incorrect. Option D shows raw numbers without suffix. Option D formats as float numbers without suffix.