|
| 1 | +""" |
| 2 | +======================== |
| 3 | +Composing Custom Legends |
| 4 | +======================== |
| 5 | +
|
| 6 | +Composing custom legends piece-by-piece. |
| 7 | +
|
| 8 | +Sometimes you don't want a legend that is explicitly tied to data that |
| 9 | +you have plotted. For example, say you have plotted 10 lines, but don't |
| 10 | +want a legend item to show up for each one. If you simply plot the lines |
| 11 | +and call ``ax.legend()``, you will get the following: |
| 12 | +""" |
| 13 | +# sphinx_gallery_thumbnail_number 2 |
| 14 | +from matplotlib import rcParams, cycler |
| 15 | +import matplotlib.pyplot as plt |
| 16 | +import numpy as np |
| 17 | + |
| 18 | +N = 10 |
| 19 | +data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)] |
| 20 | +data = np.array(data).T |
| 21 | +cmap = plt.cm.coolwarm |
| 22 | +rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N))) |
| 23 | + |
| 24 | +fig, ax = plt.subplots() |
| 25 | +lines = ax.plot(data) |
| 26 | +ax.legend(lines, loc=(1.05, .05), ) |
| 27 | + |
| 28 | +############################################################################## |
| 29 | +# In this case, we can compose a legend using Matplotlib objects that aren't |
| 30 | +# explicitly tied to the data that was plotted. For example: |
| 31 | + |
| 32 | +from matplotlib.lines import Line2D |
| 33 | +custom_lines = [Line2D([0], [0], color='b', lw=4), |
| 34 | + Line2D([0], [0], color='grey', lw=4), |
| 35 | + Line2D([0], [0], color='r', lw=4)] |
| 36 | + |
| 37 | +fig, ax = plt.subplots() |
| 38 | +lines = ax.plot(data) |
| 39 | +ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'], loc=(1.05, .8),) |
| 40 | + |
| 41 | + |
| 42 | +############################################################################### |
| 43 | +# There are many other Matplotlib objects that can be used in this way. Below |
| 44 | +# is a list of common ones. |
| 45 | + |
| 46 | +from matplotlib.patches import Patch |
| 47 | +from matplotlib.lines import Line2D |
| 48 | + |
| 49 | +legend_elements = {'Line': Line2D([0], [0], color='b', lw=4), |
| 50 | + 'Scatter': Line2D([0], [0], marker='o', color='w', |
| 51 | + markerfacecolor='g', markersize=15), |
| 52 | + 'Color Patch': Patch(facecolor='orange', edgecolor='r')} |
| 53 | +fig, ax = plt.subplots() |
| 54 | +ax.legend(legend_elements.values(), legend_elements.keys(), loc=(1.05, .8),) |
| 55 | + |
| 56 | +plt.show() |
0 commit comments