Skip to content

Reliably set the output image size #15363

@ppwwyyxx

Description

@ppwwyyxx

Bug report

I would like to use matplotlib to render a figure, and convert the figure to RGB images. I expect the output image to be of certain pixel resolution W x H.

Many online resources (eg.. https://stackoverflow.com/questions/13714454/specifying-and-saving-a-figure-with-exact-size-in-pixels) suggests the following, but works most of the time but does not work in the following case:
Code for reproduction

import matplotlib as mpl
import matplotlib.figure as mplfigure
from matplotlib.backends.backend_agg import FigureCanvasAgg
width = 956
height = 928
fig = mplfigure.Figure(frameon=False)
dpi = fig.get_dpi()
print(dpi)
fig.set_size_inches(width / dpi, height / dpi)
canvas = FigureCanvasAgg(fig)
fig.savefig("out.png")
s, (w, h) = canvas.print_to_buffer()
print(w, h)

Actual outcome

100.0
956 927

Expected outcome

I expect 928.

Matplotlib version

  • Operating system: archlinux
  • Matplotlib version: 3.0.3
  • Matplotlib backend (print(matplotlib.get_backend())): not sure if applicable to my snippet
  • Python version: 3.7
  • Jupyter version (if applicable):
  • Other libraries:
    matplotlib was installed by pip install

Metadata

Metadata

Assignees

No one assigned

    Labels

    keepItems to be ignored by the “Stale” Github Action

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions