def plot_decision_regions(X, y, classifier, resolution=0.02):
# setup marker generator and color map
markers = (\'s\', \'x\', \'o\', \'^\', \'v\')
colors = (
A ListedColormap is a colormap with listed colors. Such a colormap may be useful for showing discrete colorlevels, e.g. in an image plot (imshow
or pcolormesh
), other 2D plots like tripcolor
or a scatter plot. Also contour
plots can take colormaps and using a ListedColormap
is just one option you have to show the different contour levels in different colors.
If you already have a list of colors, you may also use this list of colors directly for your contour plot. Both options are available and the advantage of the colormap would in this case only be that you can easily create a colorbar for your plot.
See below for a comparison between directly using a list of colors and using a colormap.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors
x = np.linspace(-3,3)
X,Y = np.meshgrid(x,x)
Z = np.exp(-(X**2+Y**2))
fig, (ax, ax2) = plt.subplots(ncols=2)
colors=["red", "orange", "gold", "limegreen", "k",
"#550011", "purple", "seagreen"]
ax.set_title("contour with color list")
contour = ax.contourf(X,Y,Z, colors=colors)
ax2.set_title("contour with colormap")
cmap = matplotlib.colors.ListedColormap(colors)
contour = ax2.contourf(X,Y,Z, cmap=cmap)
fig.colorbar(contour)
plt.show()
You observe a slightly differnt behavior between the two cases, namely that the list of colors colorizes one level after the other according to the given list, while the colormap maps the range between the minimum and maximum value to the colormap, such that the first and last color are definitely in the plot, but intermediate colors (like "limegreen" in this case) are omitted, because we have one level less than colors in the color list.