1

To be more specific, How can I fix the space between a plot and legend such that if more text is included the legend won't overlap the plot?

For example, if you look at the plots below, when I add more text from "back now"(Plot 1) to "let's break hu"(Plot 2) in the first legend entry -- the legend extends to the left where it begins to cover the plot.

Is there a way to keep the space between the plot and the legend fixed? So that when there is more text the figure extends to the right rather than onto the plot itself.

Plot 1, Plot 2

Code used for the legend:

    lgd = ax.legend( patches, lgnd, loc="center right", bbox_to_anchor=(1.25, 0.5), prop=font )
Kebur Fantahun
  • 93
  • 2
  • 10
  • Please refer to [this answer](https://stackoverflow.com/a/43439132/4124317) especially the subsection "Postprocessing". If you have a specific problem implementing any of the solutions, update your question. – ImportanceOfBeingErnest Jun 23 '17 at 07:36

1 Answers1

3

Part of the answer you're looking for depends on how you made the legend and placed them in the first place. That's why people emphasize "Minimal, Complete, and Verifiable example".

To give you a simple introduction, you can control legend location using bbox_to_anchor, which accepts tuple of floats. Since you want to put the legend on the right, I would suggest using bbox_to_anchor with loc=2. This setting comes from bbox_transform. A simplified way to understand it is: bbox_to_anchor defines the relative location of the corner of the legend box and which corner of the 4 is defined by loc.

In the following example, it puts the "upper left" corner of the legend box at (1, 1) which is the upper right corner of the plot ((0,0) is the "lower left" corner of the plot). And to make it clear, I set borderaxespad to 0.

import matplotlib.pyplot as plt

plt.plot([1,2,3], label="test1")
plt.legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.)

plt.show()

enter image description here

Y. Luo
  • 5,622
  • 1
  • 18
  • 25
  • Right, sorry. Here's the code used to make the legend. 'lgd = ax.legend( patches, lgnd, loc="center right", bbox_to_anchor=(1.25, 0.5), prop=font )' – Kebur Fantahun Jun 23 '17 at 05:21
  • 1
    @Kebur Fantahun If possible and compatible with your other codes, you can use `lgd = ax.legend( patches, lgnd, loc="center left", bbox_to_anchor=(1, 0.5), prop=font )`. This can make your legend vertically centered and have a pad away from the plot. If you are not satisfied with the pad, change `1` to other values. – Y. Luo Jun 23 '17 at 06:03