|
20 | 20 | from matplotlib.cm import ScalarMappable |
21 | 21 | from matplotlib.collections import PatchCollection |
22 | 22 | from matplotlib.colors import LinearSegmentedColormap, Normalize, to_rgba |
23 | | -from matplotlib.patches import RegularPolygon |
| 23 | +from matplotlib.patches import Polygon, RegularPolygon |
24 | 24 |
|
25 | 25 | import mesa |
26 | 26 | from mesa.experimental.cell_space import ( |
@@ -501,14 +501,19 @@ def draw_continuous_space( |
501 | 501 |
|
502 | 502 |
|
503 | 503 | def draw_voronoi_grid( |
504 | | - space: VoronoiGrid, agent_portrayal: Callable, ax: Axes | None = None, **kwargs |
| 504 | + space: VoronoiGrid, |
| 505 | + agent_portrayal: Callable, |
| 506 | + ax: Axes | None = None, |
| 507 | + draw_grid: bool = True, |
| 508 | + **kwargs, |
505 | 509 | ): |
506 | 510 | """Visualize a voronoi grid. |
507 | 511 |
|
508 | 512 | Args: |
509 | 513 | space: the space to visualize |
510 | 514 | agent_portrayal: a callable that is called with the agent and returns a dict |
511 | 515 | ax: a Matplotlib Axes instance. If none is provided a new figure and ax will be created using plt.subplots |
| 516 | + draw_grid: whether to draw the grid or not |
512 | 517 | kwargs: additional keyword arguments passed to ax.scatter |
513 | 518 |
|
514 | 519 | Returns: |
@@ -541,16 +546,18 @@ def draw_voronoi_grid( |
541 | 546 |
|
542 | 547 | _scatter(ax, arguments, **kwargs) |
543 | 548 |
|
544 | | - for cell in space.all_cells: |
545 | | - polygon = cell.properties["polygon"] |
546 | | - ax.fill( |
547 | | - *zip(*polygon), |
548 | | - alpha=min(1, cell.properties[space.cell_coloring_property]), |
549 | | - c="red", |
550 | | - zorder=0, |
551 | | - ) # Plot filled polygon |
552 | | - ax.plot(*zip(*polygon), color="black") # Plot polygon edges in black |
| 549 | + def setup_voroinoimesh(cells): |
| 550 | + patches = [] |
| 551 | + for cell in cells: |
| 552 | + patch = Polygon(cell.properties["polygon"]) |
| 553 | + patches.append(patch) |
| 554 | + mesh = PatchCollection( |
| 555 | + patches, edgecolor="k", facecolor=(1, 1, 1, 0), linestyle="dotted", lw=1 |
| 556 | + ) |
| 557 | + return mesh |
553 | 558 |
|
| 559 | + if draw_grid: |
| 560 | + ax.add_collection(setup_voroinoimesh(space.all_cells.cells)) |
554 | 561 | return ax |
555 | 562 |
|
556 | 563 |
|
|
0 commit comments