Python matplotlib – draw rectangles with small inner padding (in pixels) that adjust automatically when zooming

I need to draw rectangles with small amount of INNER padding (e.g. 2 px) so that they don’t come in contact with immediately adjacent rectangles. I would like the padding to remain constant after any resize (zoom).

The example below illustrates what i’ve tried so far, which is to use ax.transData.inverted() to transform from pixels into data units, but this does not seem to give consistent results (i.e., the padding changes at different zoom levels).

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import matplotlib.pyplot as plt
import matplotlib.patches as patches
class Rectangle(patches.Rectangle):
def __init__(self, x, y, w, h, pad, **kwargs) -> None:
self._x, self._y, self._w, self._h, self._pad = x, y, w, h, pad
super().__init__((self._x, self._y), self._w, self._h, **kwargs)
def add_to_axes(self, ax) -> None:
ax.add_patch(self)
self.figure.canvas.mpl_connect("draw_event", self._on_draw)
self._ax = ax
# Keep track of current axes limits
self._xlim = ax.get_xlim()
self._ylim = ax.get_ylim()
self._update()
def _on_draw(self, event) -> None:
# Check if axes limits have changed
if self._xlim == self._ax.get_xlim() and self._ylim == self._ax.get_ylim():
return
self._update()
def _update(self) -> None:
# Update the padding
self._xlim, self._ylim = self._ax.get_xlim(), self._ax.get_ylim()
print("yes - i am a resize event")
# Calculate pixel-based padding
inv = self._ax.transData.inverted()
dx, dy = inv.transform((self._pad, self._pad)) - inv.transform((0, 0)) # <- the issue is somewhere here
print(dx)
print(dy)
# Update the rectangle's position and size
self.set_bounds((self._x + dx/2, self._y + dy/2, self._w - dx, self._h - dy))
# Example usage
fig, ax = plt.subplots()
# List of rectangles defined as (x, y, w, h)
rectangles = [
Rectangle(0, 0, 2, 3, 10),
Rectangle(2, 0, 2, 3, 10),
Rectangle(4, 0, 2, 3, 10),
Rectangle(0, 3, 6, 2, 10)
]
# Add each rectangle to the axes
for rect in rectangles:
rect.add_to_axes(ax)
# Set limits and show plot
ax.set_xlim(-1, 7)
ax.set_ylim(-1, 6)
ax.set_aspect("equal")
plt.show()
</code>
<code>import matplotlib.pyplot as plt import matplotlib.patches as patches class Rectangle(patches.Rectangle): def __init__(self, x, y, w, h, pad, **kwargs) -> None: self._x, self._y, self._w, self._h, self._pad = x, y, w, h, pad super().__init__((self._x, self._y), self._w, self._h, **kwargs) def add_to_axes(self, ax) -> None: ax.add_patch(self) self.figure.canvas.mpl_connect("draw_event", self._on_draw) self._ax = ax # Keep track of current axes limits self._xlim = ax.get_xlim() self._ylim = ax.get_ylim() self._update() def _on_draw(self, event) -> None: # Check if axes limits have changed if self._xlim == self._ax.get_xlim() and self._ylim == self._ax.get_ylim(): return self._update() def _update(self) -> None: # Update the padding self._xlim, self._ylim = self._ax.get_xlim(), self._ax.get_ylim() print("yes - i am a resize event") # Calculate pixel-based padding inv = self._ax.transData.inverted() dx, dy = inv.transform((self._pad, self._pad)) - inv.transform((0, 0)) # <- the issue is somewhere here print(dx) print(dy) # Update the rectangle's position and size self.set_bounds((self._x + dx/2, self._y + dy/2, self._w - dx, self._h - dy)) # Example usage fig, ax = plt.subplots() # List of rectangles defined as (x, y, w, h) rectangles = [ Rectangle(0, 0, 2, 3, 10), Rectangle(2, 0, 2, 3, 10), Rectangle(4, 0, 2, 3, 10), Rectangle(0, 3, 6, 2, 10) ] # Add each rectangle to the axes for rect in rectangles: rect.add_to_axes(ax) # Set limits and show plot ax.set_xlim(-1, 7) ax.set_ylim(-1, 6) ax.set_aspect("equal") plt.show() </code>
import matplotlib.pyplot as plt
import matplotlib.patches as patches

class Rectangle(patches.Rectangle):
  def __init__(self, x, y, w, h, pad, **kwargs) -> None:
    self._x, self._y, self._w, self._h, self._pad = x, y, w, h, pad

    super().__init__((self._x, self._y), self._w, self._h, **kwargs)

  def add_to_axes(self, ax) -> None:
    ax.add_patch(self)
    self.figure.canvas.mpl_connect("draw_event", self._on_draw)
    self._ax = ax
    # Keep track of current axes limits
    self._xlim = ax.get_xlim()
    self._ylim = ax.get_ylim()
    self._update()

  def _on_draw(self, event) -> None:
    # Check if axes limits have changed
    if self._xlim == self._ax.get_xlim() and self._ylim == self._ax.get_ylim():
      return
    self._update()

  def _update(self) -> None:
    # Update the padding
    self._xlim, self._ylim = self._ax.get_xlim(), self._ax.get_ylim()
    print("yes - i am a resize event")

    # Calculate pixel-based padding
    inv = self._ax.transData.inverted()
    dx, dy = inv.transform((self._pad, self._pad)) - inv.transform((0, 0)) # <- the issue is somewhere here
    print(dx)
    print(dy)

    # Update the rectangle's position and size
    self.set_bounds((self._x + dx/2, self._y + dy/2, self._w - dx, self._h - dy))

# Example usage
fig, ax = plt.subplots()

# List of rectangles defined as (x, y, w, h)
rectangles = [
  Rectangle(0, 0, 2, 3, 10),
  Rectangle(2, 0, 2, 3, 10),
  Rectangle(4, 0, 2, 3, 10),
  Rectangle(0, 3, 6, 2, 10)
]

# Add each rectangle to the axes
for rect in rectangles:
  rect.add_to_axes(ax)

# Set limits and show plot
ax.set_xlim(-1, 7)
ax.set_ylim(-1, 6)
ax.set_aspect("equal")
plt.show()

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật