mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Matplotlib property-layer rendering crashes when all layers are skipped

Open Jenil1905 opened this issue 3 weeks ago • 0 comments

*## Describe the bug

MatplotlibBackend.draw_property_layer() raises an UnboundLocalError when all property layers are skipped.

The method initializes cbar only when a property layer is rendered. If every layer is skipped because its portrayal is None, execution reaches return self.ax, cbar without cbar being assigned.

This occurs with both an empty portrayal dictionary and a callable portrayal that returns None.

Expected behavior

When all property layers are skipped, draw_property_layer() should complete without raising an exception and return (ax, None), indicating that no colorbar was created.

Existing behavior for property layers that are rendered should remain unchanged.

To Reproduce

The following minimal example reproduces the issue:

from mesa import Model
from mesa.discrete_space import OrthogonalMooreGrid
from mesa.visualization.space_renderer import SpaceRenderer

model = Model(rng=42)
model.grid = OrthogonalMooreGrid((2, 2), random=model.random)
model.grid.create_property_layer("heat", default_value=0.0)

renderer = SpaceRenderer(model, backend="matplotlib")
renderer.setup_property_layer({})
renderer.draw_property_layer()

Actual result:

UnboundLocalError: cannot access local variable 'cbar' where it is not associated with a value

The same exception occurs when using a callable portrayal:

renderer.setup_property_layer(lambda _: None)
renderer.draw_property_layer()

Additional context

  • Reproduced against Mesa upstream main at commit fe24c24ee34762de2ff85d487af14bfb5cd1dbb2.
  • Affected file: mesa/visualization/backends/matplotlib_backend.py.
  • Affected method: MatplotlibBackend.draw_property_layer().
  • The issue is caused by cbar being assigned only inside the rendering loop, while the method returns it unconditionally.
  • This is a Matplotlib backend issue, not a browser-specific issue.

Jenil1905 avatar Nov 07 '26 16:11 Jenil1905