Kebur Fantahun
Kebur Fantahun

Reputation: 93

How can I fix the space between a plot and legend so that new text doesn't change the spacing?

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 )

Upvotes: 1

Views: 6980

Answers (1)

Y. Luo
Y. Luo

Reputation: 5732

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

Upvotes: 3

Related Questions