8000 Set device pixel ratio when saving a figure · QuLogic/matplotlib@630f25f · GitHub
[go: up one dir, main page]

Skip to content

Commit 630f25f

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 0c021c7 commit 630f25f

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-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: 27 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,29 @@ def test_savefig_backend():
496498
fig.savefig("test.png", backend="pdf")
497499

498500

501+
@pytest.mark.parametrize('backend', [
502+
pytest.param('Agg', marks=[pytest.mark.backend('Agg')]),
503+
pytest.param('Cairo', marks=[pytest.mark.backend('Cairo')]),
504+
])
505+
def test_savefig_pixel_ratio(backend):
506+
fig, ax = plt.subplots()
507+
ax.plot([1, 2, 3])
508+
with io.BytesIO() as buf:
509+
fig.savefig(buf, format='png')
510+
ratio1 = Image.open(buf)
511+
ratio1.load()
512+
513+
fig, ax = plt.subplots()
514+
ax.plot([1, 2, 3])
515+
fig.canvas._set_device_pixel_ratio(2)
516+
with io.BytesIO() as buf:
517+
fig.savefig(buf, format='png')
518+
ratio2 = Image.open(buf)
519+
ratio2.load()
520+
521+
assert ratio1 == ratio2
522+
523+
499524
def test_figure_repr():
500525
fig = plt.figure(figsize=(10, 20), dpi=10)
501526
assert repr(fig) == "<Figure size 100x200 with 0 Axes>"

0 commit comments

Comments
 (0)
0