Consider this matplotlib code that creates a colorbar with a specific orientation. What will be the orientation of the colorbar?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() img = ax.imshow(np.random.rand(5,5)) cbar = fig.colorbar(img, orientation='horizontal') print(cbar.orientation)
Check the orientation parameter passed to fig.colorbar().
The orientation parameter controls the direction of the colorbar. Here it is set to horizontal, so the colorbar orientation is horizontal.
This code creates a colorbar with 5 ticks. How many tick labels will be shown on the colorbar?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() img = ax.imshow(np.random.rand(10,10)) cbar = fig.colorbar(img, ticks=[0, 0.25, 0.5, 0.75, 1]) print(len(cbar.ax.get_yticklabels()))
The number of tick labels matches the number of ticks specified in the ticks list.
Exactly 5 ticks are specified with ticks=[0, 0.25, 0.5, 0.75, 1], so there are 5 tick labels shown on the colorbar.
Examine the code below. It raises an error when run. What is the cause?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() img = ax.imshow(np.random.rand(5,5)) cbar = fig.colorbar(img, orientation='sideways')
Check the allowed values for the orientation parameter.
The orientation parameter only accepts 'vertical' or 'horizontal'. 'sideways' is invalid and causes a ValueError.
Given the following code snippet, which option correctly sets the colorbar ticks to appear inside the plot area?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() img = ax.imshow(np.random.rand(5,5)) cbar = fig.colorbar(img) # Set ticks inside here
Look for the parameter controlling tick direction.
Using tick_params(direction='in') sets the ticks to point inside the plot area.
You want to add a vertical colorbar to your plot with the label 'Intensity' and fix its width to 0.1 of the figure width. Which code snippet achieves this?
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() img = ax.imshow(np.random.rand(10,10))
Check the fraction parameter for size and use set_label for labeling.
The fraction parameter controls the fraction of the original axes to use for the colorbar width. The label is set with set_label.