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

Skip to content

Commit c3bd838

Browse files
committed
custom legends example
1 parent 22cb2d4 commit c3bd838

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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)
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'])
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 = [Line2D([0], [0], color='b', lw=4, label='Line'),
50+
Line2D([0], [0], marker='o', color='w', label='Scatter',
51+
markerfacecolor='g', markersize=15),
52+
Patch(facecolor='orange', edgecolor='r',
53+
label='Color Patch')]
54+
55+
# Create the figure
56+
# If you use `ax.legend`, you'll also need to give the labels manually.
57+
fig, ax = plt.subplots()
58+
ax.legend(handles=legend_elements, loc=(0.5, 0.5))
59+
60+
plt.show()

0 commit comments

Comments
 (0)