Matplotlib legend default location

I use a legend(loc='best')lot. I noticed that, apparently, the default is in the upper right corner if there is a lot of space available. However, I would like the loc='best'default to be in the upper left corner. (How) is it possible to change this behavior?

+4
source share
2 answers

You might be able to override the method in matplotlib, which will find the best location,

In here .

As @BrenBarn explains below and mentions in his answer, magic happens in _get_anchored_bbox, on line 875.

Add this:

from matplotlib.legend import Legend

def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
  assert loc in range(1, 11)  # called only internally
  BEST, UL, UR, LL, LR, R, CL, CR, LC, UC, C = list(xrange(11))
  anchor_coefs = {UR: "NE", UL: "NW", LL: "SW", LR: "SE", R: "E",
                  CL: "W", CR: "E", LC: "S", UC: "N", C: "C"}

  c = anchor_coefs[loc]

  fontsize = renderer.points_to_pixels(self._fontsize)
  container = parentbbox.padded(-(self.borderaxespad) * fontsize)
  anchored_box = bbox.anchored(c, container=container)
  return anchored_box.x0, anchored_box.y0         

Legend._get_anchored_bbox = _get_anchored_bbox

, . , . , legendLocationHack.py , .

+3

monkeypatch matplotlib.legend.Legend._get_anchored_bbox. :

BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = list(xrange(11))

anchor_coefs = {UR: "NE",
                UL: "NW",
                LL: "SW",
                LR: "SE",
                R: "E",
                CL: "W",
                CR: "E",
                LC: "S",
                UC: "N",
                C: "C"}

" " . _find_best_position , , , . , , , :

 BEST, UL, UR, LL, LR, R, CL, CR, LC, UC, C = list(xrange(11))

, UL UR. V- , , .

monkeypatch, _get_anchored_bbox, matplotlib.legend.Legend._get_anchored_bbox = my_get_anchored_bbox.

. , - matplotlib, , . , matplotlib , , .

+3

Source: https://habr.com/ru/post/1568064/


All Articles