Complete the code to create a discrete colorbar with 5 colors.
import matplotlib.pyplot as plt import numpy as np cmap = plt.cm.get_cmap('viridis', [1]) fig, ax = plt.subplots() fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=range(6)) plt.show()
get_cmap.The get_cmap function's second argument sets the number of discrete colors. Here, 5 creates 5 discrete colors.
Complete the code to set the colorbar ticks correctly for 4 discrete colors.
import matplotlib.pyplot as plt import numpy as np cmap = plt.cm.get_cmap('plasma', 4) fig, ax = plt.subplots() cb = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=[1]) plt.show()
The ticks should cover all boundaries of the 4 discrete colors, so 5 ticks from 0 to 4 are needed.
Fix the error in the code to create a discrete colorbar with 3 colors.
import matplotlib.pyplot as plt cmap = plt.cm.get_cmap('coolwarm', 3) fig, ax = plt.subplots() cb = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=range([1])) plt.show()
To create 3 discrete colors, the colormap must be created with 3 colors. The ticks should be from 0 to 3 to cover boundaries.
Fill both blanks to create a discrete colorbar with 6 colors and ticks from 0 to 6.
import matplotlib.pyplot as plt cmap = plt.cm.get_cmap('[1]', [2]) fig, ax = plt.subplots() fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=range(7)) plt.show()
The colormap name is 'tab10' which supports discrete colors well. The number of colors is 6 to match the ticks from 0 to 6.
Fill all three blanks to create a discrete colorbar with 4 colors, ticks from 0 to 4, and label the ticks with names.
import matplotlib.pyplot as plt import numpy as np labels = ['Low', 'Medium', 'High', 'Very High'] cmap = plt.cm.get_cmap('[1]', [2]) fig, ax = plt.subplots() cb = fig.colorbar(plt.cm.ScalarMappable(cmap=cmap), ax=ax, ticks=range([3])) cb.ax.set_yticklabels(labels) plt.show()
The 'viridis' colormap is used with 4 discrete colors. Ticks go from 0 to 4 to cover boundaries for 4 colors. The labels correspond to the 4 color segments.