|
3 | 3 | from matplotlib.colors import LinearSegmentedColormap
|
4 | 4 |
|
5 | 5 | """
|
| 6 | +Creating a colormap from a list of colors |
| 7 | +----------------------------------------- |
| 8 | +Creating a colormap from a list of colors can be done with the `from_list` |
| 9 | +method of `LinearSegmentedColormap`. You must pass a list of RGB tuples that |
| 10 | +define the mixture of colors from 0 to 1. |
| 11 | +
|
| 12 | +
|
| 13 | +Creating custom colormaps |
| 14 | +------------------------- |
| 15 | +It is also possible to create a custom mapping for a colormap. This is |
| 16 | +accomplished by creating dictionary that specifies how the RGB channels |
| 17 | +change from one end of the cmap to the other. |
6 | 18 |
|
7 | 19 | Example: suppose you want red to increase from 0 to 1 over the bottom
|
8 | 20 | half, green to do the same over the middle half, and blue over the top
|
|
55 | 67 | never used.
|
56 | 68 |
|
57 | 69 | """
|
| 70 | +# Make some illustrative fake data: |
| 71 | + |
| 72 | +x = np.arange(0, np.pi, 0.1) |
| 73 | +y = np.arange(0, 2*np.pi, 0.1) |
| 74 | +X, Y = np.meshgrid(x, y) |
| 75 | +Z = np.cos(X) * np.sin(Y) * 10 |
| 76 | + |
| 77 | + |
| 78 | +# --- Colormaps from a list --- |
58 | 79 |
|
| 80 | +colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # R -> G -> B |
| 81 | +n_bins = [2, 5, 10, 100] # Discretizes the interpolation into bins |
| 82 | +cmap_name = 'my_list' |
| 83 | +f, axs = plt.subplots(1, 4, figsize=(10, 5)) |
| 84 | +for n_bin, ax in zip(n_bins, axs): |
| 85 | + # Create the colormap |
| 86 | + cm = LinearSegmentedColormap.from_list( |
| 87 | + cmap_name, colors, N=n_bin) |
| 88 | + # Fewer bins will result in "coarser" colomap interpolation |
| 89 | + im = ax.imshow(Z, interpolation='nearest', cmap=cm) |
| 90 | + ax.set_title("N bins: %s" % n_bin) |
| 91 | + |
| 92 | + |
| 93 | +# --- Custom colormaps --- |
59 | 94 |
|
60 | 95 | cdict1 = {'red': ((0.0, 0.0, 0.0),
|
61 | 96 | (0.5, 0.0, 0.1),
|
|
130 | 165 | plt.register_cmap(name='BlueRed3', data=cdict3) # optional lut kwarg
|
131 | 166 | plt.register_cmap(name='BlueRedAlpha', data=cdict4)
|
132 | 167 |
|
133 |
| -# Make some illustrative fake data: |
134 |
| - |
135 |
| -x = np.arange(0, np.pi, 0.1) |
136 |
| -y = np.arange(0, 2*np.pi, 0.1) |
137 |
| -X, Y = np.meshgrid(x, y) |
138 |
| -Z = np.cos(X) * np.sin(Y) * 10 |
139 |
| - |
140 | 168 | # Make the figure:
|
141 | 169 |
|
142 | 170 | plt.figure(figsize=(6, 9))
|
|
0 commit comments