Consider this code snippet that creates a colorbar with custom tick labels. What will be the printed list of tick labels?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() img = ax.imshow(np.random.rand(5,5), cmap='viridis') cbar = fig.colorbar(img) cbar.set_ticks([0.2, 0.5, 0.8]) ticks = cbar.ax.get_yticklabels() labels = [tick.get_text() for tick in ticks] print(labels)
Remember that get_yticklabels() returns label objects which may not have text set until drawn.
The get_yticklabels() method returns label objects but their text is empty until the figure is drawn. So the printed list is empty strings.
This code creates a colorbar with a fixed number of ticks. How many ticks will appear on the colorbar?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() img = ax.imshow(np.random.rand(10,10), cmap='plasma') cbar = fig.colorbar(img, ticks=np.linspace(0,1,5)) print(len(cbar.ax.get_yticks()))
Check how many values are in np.linspace(0,1,5).
The ticks argument sets exactly 5 ticks, so get_yticks() returns 5 values.
Look at this code that tries to format colorbar tick labels. What error does it raise?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() img = ax.imshow(np.random.rand(5,5), cmap='cool') cbar = fig.colorbar(img) cbar.ax.yaxis.set_major_formatter('{:.2f}')
Check what type set_major_formatter expects as argument.
The set_major_formatter method expects a Formatter object, not a string. Passing a string causes a TypeError because strings are not callable.
You want to show colorbar tick labels as percentages (e.g., 20%, 50%). Which option correctly formats the colorbar ticks?
import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import FuncFormatter fig, ax = plt.subplots() img = ax.imshow(np.random.rand(5,5), cmap='inferno') cbar = fig.colorbar(img)
Use FuncFormatter to create a custom label format function.
Option A uses FuncFormatter with a lambda that multiplies the tick value by 100 and adds a percent sign, which is the correct way.
Option A manually sets labels but does not update ticks properly.
Option A passes a string instead of a Formatter object, causing error.
Option A tries to assign formatter attribute directly, which is not correct usage.
cbar.ax.invert_yaxis() on a vertical colorbar?In matplotlib, what happens when you call invert_yaxis() on the colorbar's axis?
Think about what inverting the y-axis means visually.
Calling invert_yaxis() flips the vertical axis, so the color gradient is reversed vertically. High values appear at the bottom instead of top.