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

Skip to content

Commit 37c5fc4

Browse files
committed
Set device pixel ratio when saving a figure
Otherwise, `FigureCanvasBase.get_width_height` returns a size scaled down by the current pixel ratio, even though the DPI is not scaled up. This causes the saved figure to be cropped.
1 parent e371623 commit 37c5fc4

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

lib/matplotlib/backend_bases.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2259,6 +2259,7 @@ def print_figure(
22592259
# Remove the figure manager, if any, to avoid resizing the GUI widget.
22602260
with cbook._setattr_cm(self, manager=None), \
22612261
cbook._setattr_cm(self.figure, dpi=dpi), \
2262+
cbook._setattr_cm(canvas, _device_pixel_ratio=1), \
22622263
cbook._setattr_cm(canvas, _is_saving=True), \
22632264
ExitStack() as stack:
22642265

lib/matplotlib/tests/test_figure.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66
from types import SimpleNamespace
77
import warnings
88

9+
import numpy as np
10+
import pytest
11+
from PIL import Image
12+
913
import matplotlib as mpl
1014
from matplotlib import cbook, rcParams
1115
from matplotlib._api.deprecation import MatplotlibDeprecationWarning
@@ -16,8 +20,6 @@
1620
import matplotlib.pyplot as plt
1721
import matplotlib.dates as mdates
1822
import matplotlib.gridspec as gridspec
19-
import numpy as np
20-
import pytest
2123

2224

2325
@image_comparison(['figure_align_labels'], extensions=['png', 'svg'],
@@ -496,6 +498,24 @@ def test_savefig_backend():
496498
fig.savefig("test.png", backend="pdf")
497499

498500

501+
@pytest.mark.parametrize('backend', ['Agg', 'Cairo'])
502+
def test_savefig_pixel_ratio(backend):
503+
plt.switch_backend(backend)
504+
505+
fig = plt.figure()
506+
with io.BytesIO() as buf:
507+
fig.savefig(buf, format='png')
508+
ratio1 = Image.open(buf)
509+
510+
fig = plt.figure()
511+
fig.canvas._set_device_pixel_ratio(2)
512+
with io.BytesIO() as buf:
513+
fig.savefig(buf, format='png')
514+
ratio2 = Image.open(buf)
515+
516+
assert ratio1.size == ratio2.size
517+
518+
499519
def test_figure_repr():
500520
fig = plt.figure(figsize=(10, 20), dpi=10)
501521
assert repr(fig) == "<Figure size 100x200 with 0 Axes>"

0 commit comments

Comments
 (0)