Set the location of the legend. .. versionadded:: 3.8 Parameters ---------- %(_legend_kw_set_loc_doc)s
(self, loc=None)
| 662 | |
| 663 | @_docstring.interpd |
| 664 | def set_loc(self, loc=None): |
| 665 | """ |
| 666 | Set the location of the legend. |
| 667 | |
| 668 | .. versionadded:: 3.8 |
| 669 | |
| 670 | Parameters |
| 671 | ---------- |
| 672 | %(_legend_kw_set_loc_doc)s |
| 673 | """ |
| 674 | loc0 = loc |
| 675 | self._loc_used_default = loc is None |
| 676 | if loc is None: |
| 677 | loc = mpl.rcParams["legend.loc"] |
| 678 | if not self.isaxes and loc in [0, 'best']: |
| 679 | loc = 'upper right' |
| 680 | |
| 681 | type_err_message = ("loc must be string, coordinate tuple, or" |
| 682 | f" an integer 0-10, not {loc!r}") |
| 683 | |
| 684 | # handle outside legends: |
| 685 | self._outside_loc = None |
| 686 | if isinstance(loc, str): |
| 687 | if loc.split()[0] == 'outside': |
| 688 | # strip outside: |
| 689 | loc = loc.split('outside ')[1] |
| 690 | # strip "center" at the beginning |
| 691 | self._outside_loc = loc.replace('center ', '') |
| 692 | # strip first |
| 693 | self._outside_loc = self._outside_loc.split()[0] |
| 694 | locs = loc.split() |
| 695 | if len(locs) > 1 and locs[0] in ('right', 'left'): |
| 696 | # locs doesn't accept "left upper", etc, so swap |
| 697 | if locs[0] != 'center': |
| 698 | locs = locs[::-1] |
| 699 | loc = locs[0] + ' ' + locs[1] |
| 700 | # check that loc is in acceptable strings |
| 701 | loc = _api.getitem_checked(self.codes, loc=loc) |
| 702 | elif np.iterable(loc): |
| 703 | # coerce iterable into tuple |
| 704 | loc = tuple(loc) |
| 705 | # validate the tuple represents Real coordinates |
| 706 | if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc): |
| 707 | raise ValueError(type_err_message) |
| 708 | elif isinstance(loc, int): |
| 709 | # validate the integer represents a string numeric value |
| 710 | if loc < 0 or loc > 10: |
| 711 | raise ValueError(type_err_message) |
| 712 | else: |
| 713 | # all other cases are invalid values of loc |
| 714 | raise ValueError(type_err_message) |
| 715 | |
| 716 | if self.isaxes and self._outside_loc: |
| 717 | raise ValueError( |
| 718 | f"'outside' option for loc='{loc0}' keyword argument only " |
| 719 | "works for figure legends") |
| 720 | |
| 721 | if not self.isaxes and loc == 0: |