Skip to content

[Bug]: figure canvas size does not always match figure size and dpi #30310

@fangq

Description

@fangq

Bug summary

I stumbled upon this issue when I tested the codes in #30305.

basically, I am trying to create a canvas buffer with a prescribed pixel size. The formula I understood that buffer_rgba() output should follow is the figure's size in inch, multiplied by the dpi setting.

However, upon scanning a range of desired sizes, I found that at a small subset of sizes, the buffer_rgba() output buffer size failed to match - and it is always 1 pixel larger than desired.

The below script tests this for output pixel size between 1 and 1000, and it discovered 21 outliers, see below

my 11yr old took a quick look and found some vague patterns - 29 * 2^N is always in this list, other than that, the gap between the adjacent outlier frequently show 25 for some reason - I do not believe these are related to numerical precision, but perhaps it may be related to rounding algorithms?

  i      w   h
[29, [28, 28]]
[58, [57, 57]]
[116, [115, 115]]
[205, [204, 204]]
[207, [206, 206]]
[232, [231, 231]]
[410, [409, 409]]
[414, [413, 413]]
[439, [438, 438]]
[464, [463, 463]]
[489, [488, 488]]
[803, [802, 802]]
[820, [819, 819]]
[828, [827, 827]]
[845, [844, 844]]
[853, [852, 852]]
[878, [877, 877]]
[903, [902, 902]]
[928, [927, 927]]
[953, [952, 952]]
[978, [977, 977]]

Code for reproduction

import matplotlib.pyplot as plt

for i in range(1, 1000):
  fig = plt.figure(figsize=(i * 0.01, i * 0.01), dpi=100)
  plt.draw()
  fig.canvas.draw()
  w, h = fig.canvas.get_width_height()
  plt.close(fig)
  if not (i == w and i == h):
    print([i, [w, h]])

Actual outcome

at some figure sizes, the output buffer has an extra pixel, and this is not predictable

Expected outcome

expect the output buffer size should match figure size in inch * dpi

Additional information

No response

Operating system

Ubuntu

Matplotlib Version

3.10.3

Matplotlib Backend

No response

Python version

3.10

Jupyter version

No response

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    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