-
Notifications
You must be signed in to change notification settings - Fork 916
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Implement Altair version of grid visualization
_draw_grid is derived from https://github.com/Princeton-CDH/simulating-risk/blob/907c290e12c97b28aa9ce9c80ea7fc52a4f280ae/simulatingrisk/hawkdove/server.py#L114-L171 Co-authored-by: rlskoeser <[email protected]>
- Loading branch information
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import contextlib | ||
from typing import Optional | ||
|
||
import pandas as pd | ||
import solara | ||
|
||
with contextlib.suppress(ImportError): | ||
import altair as alt | ||
|
||
@solara.component | ||
def SpaceAltair(model, agent_portrayal, dependencies: Optional[list[any]] = None): | ||
space = getattr(model, "grid", None) | ||
if space is None: | ||
# Sometimes the space is defined as model.space instead of model.grid | ||
space = model.space | ||
chart = _draw_grid(space, agent_portrayal) | ||
solara.FigureAltair(chart) | ||
|
||
|
||
def _draw_grid(space, agent_portrayal): | ||
def portray(g): | ||
all_agent_data = [] | ||
for content, (x, y) in space.coord_iter(): | ||
if not content: | ||
continue | ||
if not hasattr(content, "__iter__"): | ||
# Is a single grid | ||
content = [content] | ||
for agent in content: | ||
# use all data from agent portrayal, and add x,y coordinates | ||
agent_data = agent_portrayal(agent) | ||
agent_data["x"] = x | ||
agent_data["y"] = y | ||
all_agent_data.append(agent_data) | ||
return all_agent_data | ||
|
||
all_agent_data = portray(space) | ||
df = pd.DataFrame(all_agent_data) | ||
chart = ( | ||
alt.Chart(df) | ||
.mark_point(filled=True) | ||
.encode( | ||
# no x-axis label | ||
x=alt.X("x", axis=None), | ||
# no y-axis label | ||
y=alt.Y("y", axis=None), | ||
size=alt.Size("size"), | ||
color=alt.Color("color"), | ||
) | ||
# .configure_view(strokeOpacity=0) # hide grid/chart lines | ||
) | ||
return chart |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters