Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 058dda7

Browse files
committed
custom legends example
1 parent 22cb2d4 commit 058dda7

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""
2+
========================
3+
Composing Custom Legends
4+
========================
5+
6+
Composing custom legends piece-by-piece.
7+
8+
.. note::
9+
10+
For more information on creating and customizing legends, see the following
11+
pages:
12+
13+
* :ref:`sphx_glr_tutorials_intermediate_legend_guide.py`
14+
* :ref:`sphx_glr_gallery_text_labels_and_annotations_legend_demo.py`
15+
16+
Sometimes you don't want a legend that is explicitly tied to data that
17+
you have plotted. For example, say you have plotted 10 lines, but don't
18+
want a legend item to show up for each one. If you simply plot the lines
19+
and call ``ax.legend()``, you will get the following:
20+
"""
21+
# sphinx_gallery_thumbnail_number = 2
22+
from matplotlib import rcParams, cycler
23+
import matplotlib.pyplot as plt
24+
import numpy as np
25+
26+
N = 10
27+
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
28+
data = np.array(data).T
29+
cmap = plt.cm.coolwarm
30+
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))
31+
32+
fig, ax = plt.subplots()
33+
lines = ax.plot(data)
34+
ax.legend(lines)
35+
36+
##############################################################################
37+
# Note that one legend item per line was created.
38+
# In this case, we can compose a legend using Matplotlib objects that aren't
39+
# explicitly tied to the data that was plotted. For example:
40+
41+
from matplotlib.lines import Line2D
42+
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
43+
Line2D([0], [0], color=cmap(.5), lw=4),
44+
Line2D([0], [0], color=cmap(1.), lw=4)]
45+
46+
fig, ax = plt.subplots()
47+
lines = ax.plot(data)
48+
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])
49+
50+
51+
###############################################################################
52+
# There are many other Matplotlib objects that can be used in this way. In the
53+
# code below we've listed a few common ones.
54+
55+
from matplotlib.patches import Patch
56+
from matplotlib.lines import Line2D
57+
58+
legend_elements = [Line2D([0], [0], color='b', lw=4, label='Line'),
59+
Line2D([0], [0], marker='o', color='w', label='Scatter',
60+
markerfacecolor='g', markersize=15),
61+
Patch(facecolor='orange', edgecolor='r',
62+
label='Color Patch')]
63+
64+
# Create the figure
65+
fig, ax = plt.subplots()
66+
ax.legend(handles=legend_elements, loc='center')
67+
68+
plt.show()

0 commit comments

Comments
 (0)