|
| 1 | +""" |
| 2 | +Showcases legend entries with more than one legend key. |
| 3 | +""" |
1 | 4 | import matplotlib.pyplot as plt |
2 | 5 | from matplotlib.legend_handler import HandlerTuple |
3 | 6 |
|
4 | 7 | fig, (ax1, ax2) = plt.subplots(2, 1) |
| 8 | + |
| 9 | +# First plot: two legend keys for a single entry |
5 | 10 | p1 = ax1.scatter([1], [5], c='r', marker='s', s=100) |
6 | 11 | p2 = ax1.scatter([3], [2], c='b', marker='o', s=100) |
| 12 | +# `plot` returns a list, but we want the handle - thus the comma on the left |
| 13 | +p3, = ax1.plot([1, 5], [4, 4], 'm-d') |
7 | 14 |
|
8 | | -l = ax1.legend([(p1, p2)], ['points'], scatterpoints=1, |
9 | | - handler_map={tuple: HandlerTuple(ndivide=0)}) |
| 15 | +# Assign two of the handles to the same legend entry by putting them in a tuple |
| 16 | +# and using a generic handler map (which would be used for any additional |
| 17 | +# tuples of handles like (p1, p3)). |
| 18 | +l = ax1.legend([(p1, p3), p2], ['two keys', 'one key'], scatterpoints=1, |
| 19 | + numpoints=1, handler_map={tuple: HandlerTuple(ndivide=0)}) |
10 | 20 |
|
11 | | -ind = [1, 2, 3] |
12 | | -pos1 = [1, 3, 2] |
13 | | -neg1 = [2, 1, 4] |
14 | | -width = [0.5, 0.5, 0.5] |
| 21 | +# Second plot: plot two bar charts on top of each other and change the padding |
| 22 | +# between the legend keys |
| 23 | +x_left = [1, 2, 3] |
| 24 | +y_pos = [1, 3, 2] |
| 25 | +y_neg = [2, 1, 4] |
15 | 26 |
|
16 | | -rpos1 = ax2.bar(ind, pos1, width=0.5, color='k', label='+1') |
17 | | -rneg1 = ax2.bar(ind, neg1, width=0.5, color='w', hatch='///', label='-1') |
| 27 | +rneg = ax2.bar(x_left, y_neg, width=0.5, color='w', hatch='///', label='-1') |
| 28 | +rpos = ax2.bar(x_left, y_pos, width=0.5, color='k', label='+1') |
18 | 29 |
|
19 | | -l = ax2.legend([(rpos1, rneg1)], ['Test'], |
20 | | - handler_map={(rpos1, rneg1): HandlerTuple(ndivide=0, pad=0.)}) |
| 30 | +# Treat each legend entry differently by using specific `HandlerTuple`s |
| 31 | +l = ax2.legend([(rpos, rneg), (rneg, rpos)], ['pad!=0', 'pad=0'], |
| 32 | + handler_map={(rpos, rneg): HandlerTuple(ndivide=0), |
| 33 | + (rneg, rpos): HandlerTuple(ndivide=0, pad=0.)}) |
21 | 34 |
|
22 | 35 | plt.show() |
0 commit comments