8000 Surprising behavior of legend when both `loc='best'` and `bbox_to_anchor` are used. · Issue #8366 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content
Surprising behavior of legend when both loc='best' and bbox_to_anchor are used.  #8366
Closed
@afvincent

Description

@afvincent

Bug (?) report

Bug summary

I do not know if it was ever intended to combine the bbox_to_anchor and the loc kwargs in legend. But it results in a behavior that I find rather surprising.

Code for reproduction

import matplotlib.pyplot as plt


def do_plot(ax, loc='best', bbox_to_anchor=(0.5, 0.5), color='black'):
    ax.plot([0, 1], color=color, label='A label')
    ax.set_ylim(top=3)
    ax.legend(loc=loc, bbox_to_anchor=bbox_to_anchor)
    # Cosmeticks
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())
    ax.set_title("loc={l}\nbbox_to_anchor={b}".format(l=loc, b=bbox_to_anchor))
    return ax

fig, ((ax0, ax1), (ax2, ax3), (ax4, ax5)) = plt.subplots(nrows=3, ncols=2)
# First row
do_plot(ax0, color='r', loc='upper right', bbox_to_anchor=(-0.001, 1))
do_plot(ax1, color='g', loc='best', bbox_to_anchor=(-0.001, 1))
# Second row
do_plot(ax2, color='b', loc='upper left', bbox_to_anchor=(0.001, 1))
do_plot(ax3, color='y', loc='best', bbox_to_anchor=(0.001, 1))
# Third row
do_plot(ax4, color='m', loc='upper left', bbox_to_anchor=(0.1, 1))
do_
5B26
plot(ax5, color='c', loc='best', bbox_to_anchor=(0.1, 1))

fig.subplots_adjust(left=0.2, hspace=0.5, wspace=0.75, bottom=0.05, top=0.90)
plt.show()

Actual outcome
Matplotlib 2.0.0:
confusing_legend_position_with_a_bbox_to_anchor_with_mpl2 0 0

Matplotlib 1.5.1:
confusing_legend_position_with_a_bbox_to_anchor_with_mpl1 5 1

Expected outcome

  • First row is fine for me: 'best' <- 'upper right' because else the legend frame would have overlapped with the left spine.
  • Second and third rows seem weird to me: why would the best location not be something like 'upper left'?

If I am not the only one to find the behavior of the left column a bit surprising, then the real problem is that it is now the default legend behavior in 2.0 if the user only provide a bbox_to_anchor but no loc, isn't it?

Matplotlib version
Tested on Linux (CentOS 7), with Python 2.7 and mpl 2.0.0 and 1.5.1 (installed from conda).

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0