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

Skip to content

Commit 6657fe1

Browse files
authored
Merge pull request #9451 from choldgraf/custom_legend
custom legends example
2 parents ffc20d4 + 561180a commit 6657fe1

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
# Fixing random state for reproducibility
27+
np.random.seed(19680801)
28+
29+
N = 10
30+
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
31+
data = np.array(data).T
32+
cmap = plt.cm.coolwarm
33+
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))
34+
35+
fig, ax = plt.subplots()
36+
lines = ax.plot(data)
37+
ax.legend(lines)
38+
39+
##############################################################################
40+
# Note that one legend item per line was created.
41+
# In this case, we can compose a legend using Matplotlib objects that aren't
42+
# explicitly tied to the data that was plotted. For example:
43+
44+
from matplotlib.lines import Line2D
45+
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
46+
Line2D([0], [0], color=cmap(.5), lw=4),
47+
Line2D([0], [0], color=cmap(1.), lw=4)]
48+
49+
fig, ax = plt.subplots()
50+
lines = ax.plot(data)
51+
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])
52+
53+
54+
###############################################################################
55+
# There are many other Matplotlib objects that can be used in this way. In the
56+
# code below we've listed a few common ones.
57+
58+
from matplotlib.patches import Patch
59+
from matplotlib.lines import Line2D
60+
61+
legend_elements = [Line2D([0], [0], color='b', lw=4, label='Line'),
62+
Line2D([0], [0], marker='o', color='w', label='Scatter',
63+
markerfacecolor='g', markersize=15),
64+
Patch(facecolor='orange', edgecolor='r',
65+
label='Color Patch')]
66+
67+
# Create the figure
68+
fig, ax = plt.subplots()
69+
ax.legend(handles=legend_elements, loc='center')
70+
71+
plt.show()

0 commit comments

Comments
 (0)