Matplotlib 3.0 Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

The following code block displays three plots; the first one uses the standard colormap, coolwarm, and the other two use user-defined discrete colormaps. Of the two user-defined ones, the first one uses pure RED (1, 0, 0), GREEN (0, 1, 0), and BLUE (0, 0, 1) colors, and the other uses a mix of RGB colors [(1, 0.5, 0), (0.25, 1, 0), (0, 0.5, 1)] to generate three discrete colors. Please note in the first colormap tuple (1, 0, 0), only red is 1; green and blue are zeros. In the second one, the first and second colors are (1, 0.5, 0), and (0.25, 1, 0) means they are a combination of red and green, and the third color is a combination of green and blue.

We are using three discrete colors here, since we have three clusters in the input dataset. We should have as many colors as the number of clusters:

  1. Read the Iris data from Excel and replace text class names with numeric values:
iris = pd.read_csv('iris_dataset.csv', delimiter=',')
iris['species'] = iris['species'].map({"setosa" : 0, "versicolor" :
1, "virginica" : 2})
  1. Define the figure and its layout:
fig, axs = plt.subplots(1,3, figsize=(9,6))
fig.subplots_adjust(left=0.0, bottom=0.05, right=0.9, top=0.95,
wspace=0.6)
  1. Define a function to plot the graph:
def plot_graph(axes, cm, cbaxs):
im = axes.scatter(iris.petal_length, iris.petal_width,
s=10*iris.petal_length*iris.petal_width, c=iris.species,
cmap = cm)
caxs = plt.axes(cbaxs)
fig.colorbar(im, caxs, ticks=range(3), label='clusetr #')
  1. Plot the Iris dataset clusters with three colors chosen from the pre-defined colormap, coolwarm:
cbaxs = [0.24, 0.05, 0.03, 0.85] # left, bottom, width and height
plot_graph(axs[0], plt.cm.get_cmap('coolwarm', 3), cbaxs)
  1. Plot the Iris data clusters with custom-defined colors that are pure red, green, and blue:
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # R -> G -> B
cm = LinearSegmentedColormap.from_list('custom_RGB_cmap', colors,
N=3)
cbaxs = [0.58, 0.05, 0.03, 0.85]
plot_graph(axs[1], cm, cbaxs)
  1. Plot Iris data clusters with custom-defined colors that are a mixed combination of colors:
colors = [(1, 0.5, 0), (0.25, 0.5, 0.25), (0, 0.5, 1)] # R -> G -> B
cm = LinearSegmentedColormap.from_list('dummy', colors, N=3)
cbaxs = [0.95, 0.05, 0.03, 0.85]
plot_graph(axs[2], cm, cbaxs)
  1. Display the figure on the screen:
plt.show()