Thanks to visit codestin.com
Credit goes to github.com

Skip to content

legend is not present in the generated image if I use 'tight' for bbox_inches #10194

Closed
@jdhao

Description

@jdhao

summary of the problem

I tried to put legend outside of the axes. If I use fig.legend() method to produce legend and use bbox_inches='tight' in savefig() method. The legend is not present in the produced image (using the argument bbox_extra_artists also does not work). If I use ax.legend() instead, the legend is present in the saved image.

Code for reproduction

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

x = np.arange(-5, 5, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

y3 = np.sin(2*x)
y4 = np.cos(2*x)

fig, (ax1, ax2) = plt.subplots(ncols=1, nrows=2, figsize=(10, 6))

ax1.plot(x, y1, label='sin')
ax1.plot(x, y2, label='cos')

ax2.plot(x, y3, label='sin')
ax2.plot(x, y4, label='cos')

handles, labels = ax1.get_legend_handles_labels()
# following code does not work
legend = fig.legend(handles, labels, loc='lower left', ncol=2, frameon=False,
              bbox_to_anchor=(0.12, 0.88))
plt.savefig('test.jpg', bbox_extra_artists=[legend,], bbox_inches='tight')

# following code works
# legend = ax1.legend(handles, labels, ncol=2, frameon=False,
#                     loc='lower left', bbox_to_anchor=(-0.01, 1.2))
# plt.savefig('test.jpg', bbox_inches='tight')
plt.show()

outcome

The saved images are different if I use different legend method.

using fig.legend method

image

using ax.legend method

image

Matplotlib version

  • Operating system: Windows 8.1 and Linux (CentOS 7) (This problem is maybe platform independent)
  • Matplotlib version: 2.0.2(Linux), 2.0.0 (Windows)
  • Matplotlib backend: Qt5Agg
  • Python version: 3.5.2 (Windows), 3.6.2 (Linux)

The matplotlib and python are all distributed with Anaconda.

quesiton

Is this a bug or something I do not know. Maybe there is difference between fig.legend and ax.legend method?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions