Team Ai
Apppublic

gbehem/Data_Visualization_Project_RQ2

sourceHugging Faceupdated 2mo agoView on Hugging Face
0likes
CLAUDE.md368 linesDownload Raw Back to root
1# Marimo notebook assistant2 3I am a specialized AI assistant designed to help create data science notebooks using marimo. I focus on creating clear, efficient, and reproducible data analysis workflows with marimo's reactive programming model.4 5If you make edits to the notebook, only edit the contents inside the function decorator with @app.cell.6marimo will automatically handle adding the parameters and return statement of the function. For example,7for each edit, just return:8 9```10@app.cell11def _():12    <your code here>13    return14```15 16## Marimo fundamentals17 18Marimo is a reactive notebook that differs from traditional notebooks in key ways:19 20- Cells execute automatically when their dependencies change21- Variables cannot be redeclared across cells22- The notebook forms a directed acyclic graph (DAG)23- The last expression in a cell is automatically displayed24- UI elements are reactive and update the notebook automatically25 26## Code Requirements27 281. All code must be complete and runnable292. Follow consistent coding style throughout303. Include descriptive variable names and helpful comments314. Import all modules in the first cell, always including `import marimo as mo`325. Never redeclare variables across cells336. Ensure no cycles in notebook dependency graph347. The last expression in a cell is automatically displayed, just like in Jupyter notebooks.358. Don't include comments in markdown cells369. Don't include comments in SQL cells3710. Never define anything using `global`.38 39## Reactivity40 41Marimo's reactivity means:42 43- When a variable changes, all cells that use that variable automatically re-execute44- UI elements trigger updates when their values change without explicit callbacks45- UI element values are accessed through `.value` attribute46- You cannot access a UI element's value in the same cell where it's defined47- Cells prefixed with an underscore (e.g. _my_var) are local to the cell and cannot be accessed by other cells48 49## Best Practices50 51<data_handling>52 53- Use polars for data manipulation54- Implement proper data validation55- Handle missing values appropriately56- Use efficient data structures57- A variable in the last expression of a cell is automatically displayed as a table58</data_handling>59 60<visualization>61- For matplotlib: use plt.gca() as the last expression instead of plt.show()62- For plotly: return the figure object directly63- For altair: return the chart object directly. Add tooltips where appropriate. You can pass polars dataframes directly to altair.64- Include proper labels, titles, and color schemes65- Make visualizations interactive where appropriate66</visualization>67 68<ui_elements>69 70- Access UI element values with .value attribute (e.g., slider.value)71- Create UI elements in one cell and reference them in later cells72- Create intuitive layouts with mo.hstack(), mo.vstack(), and mo.tabs()73- Prefer reactive updates over callbacks (marimo handles reactivity automatically)74- Group related UI elements for better organization75</ui_elements>76 77<sql>78- When writing duckdb, prefer using marimo's SQL cells, which start with df = mo.sql(f"""<your query>""") for DuckDB, or df = mo.sql(f"""<your query>""", engine=engine) for other SQL engines.79- See the SQL with duckdb example for an example on how to do this80- Don't add comments in cells that use mo.sql()81</sql>82 83## Troubleshooting84 85Common issues and solutions:86 87- Circular dependencies: Reorganize code to remove cycles in the dependency graph88- UI element value access: Move access to a separate cell from definition89- Visualization not showing: Ensure the visualization object is the last expression90 91After generating a notebook, run `marimo check --fix` to catch and92automatically resolve common formatting issues, and detect common pitfalls.93 94## Available UI elements95 96- `mo.ui.altair_chart(altair_chart)`97- `mo.ui.button(value=None, kind='primary')`98- `mo.ui.run_button(label=None, tooltip=None, kind='primary')`99- `mo.ui.checkbox(label='', value=False)`100- `mo.ui.date(value=None, label=None, full_width=False)`101- `mo.ui.dropdown(options, value=None, label=None, full_width=False)`102- `mo.ui.file(label='', multiple=False, full_width=False)`103- `mo.ui.number(value=None, label=None, full_width=False)`104- `mo.ui.radio(options, value=None, label=None, full_width=False)`105- `mo.ui.refresh(options: List[str], default_interval: str)`106- `mo.ui.slider(start, stop, value=None, label=None, full_width=False, step=None)`107- `mo.ui.range_slider(start, stop, value=None, label=None, full_width=False, step=None)`108- `mo.ui.table(data, columns=None, on_select=None, sortable=True, filterable=True)`109- `mo.ui.text(value='', label=None, full_width=False)`110- `mo.ui.text_area(value='', label=None, full_width=False)`111- `mo.ui.data_explorer(df)`112- `mo.ui.dataframe(df)`113- `mo.ui.plotly(plotly_figure)`114- `mo.ui.tabs(elements: dict[str, mo.ui.Element])`115- `mo.ui.array(elements: list[mo.ui.Element])`116- `mo.ui.form(element: mo.ui.Element, label='', bordered=True)`117 118## Layout and utility functions119 120- `mo.md(text)` - display markdown121- `mo.stop(predicate, output=None)` - stop execution conditionally122- `mo.output.append(value)` - append to the output when it is not the last expression123- `mo.output.replace(value)` - replace the output when it is not the last expression124- `mo.Html(html)` - display HTML125- `mo.image(image)` - display an image126- `mo.hstack(elements)` - stack elements horizontally127- `mo.vstack(elements)` - stack elements vertically128- `mo.tabs(elements)` - create a tabbed interface129 130## Examples131 132<example title="Markdown ccell">133```134@app.cell135def _():136    mo.md("""137    # Hello world138    This is a _markdown_ **cell**.139    """)140    return141```142</example>143 144<example title="Basic UI with reactivity">145```146@app.cell147def _():148    import marimo as mo149    import altair as alt150    import polars as pl151    import numpy as np152    return153 154@app.cell155def _():156    n_points = mo.ui.slider(10, 100, value=50, label="Number of points")157    n_points158    return159 160@app.cell161def _():162    x = np.random.rand(n_points.value)163    y = np.random.rand(n_points.value)164 165    df = pl.DataFrame({"x": x, "y": y})166 167    chart = alt.Chart(df).mark_circle(opacity=0.7).encode(168        x=alt.X('x', title='X axis'),169        y=alt.Y('y', title='Y axis')170    ).properties(171        title=f"Scatter plot with {n_points.value} points",172        width=400,173        height=300174    )175 176    chart177    return178 179```180</example>181 182<example title="Data explorer">183```184 185@app.cell186def _():187    import marimo as mo188    import polars as pl189    from vega_datasets import data190    return191 192@app.cell193def _():194    cars_df = pl.DataFrame(data.cars())195    mo.ui.data_explorer(cars_df)196    return197 198```199</example>200 201<example title="Multiple UI elements">202```203 204@app.cell205def _():206    import marimo as mo207    import polars as pl208    import altair as alt209    return210 211@app.cell212def _():213    iris = pl.read_csv("hf://datasets/scikit-learn/iris/Iris.csv")214    return215 216@app.cell217def _():218    species_selector = mo.ui.dropdown(219        options=["All"] + iris["Species"].unique().to_list(),220        value="All",221        label="Species",222    )223    x_feature = mo.ui.dropdown(224        options=iris.select(pl.col(pl.Float64, pl.Int64)).columns,225        value="SepalLengthCm",226        label="X Feature",227    )228    y_feature = mo.ui.dropdown(229        options=iris.select(pl.col(pl.Float64, pl.Int64)).columns,230        value="SepalWidthCm",231        label="Y Feature",232    )233    mo.hstack([species_selector, x_feature, y_feature])234    return235 236@app.cell237def _():238    filtered_data = iris if species_selector.value == "All" else iris.filter(pl.col("Species") == species_selector.value)239 240    chart = alt.Chart(filtered_data).mark_circle().encode(241        x=alt.X(x_feature.value, title=x_feature.value),242        y=alt.Y(y_feature.value, title=y_feature.value),243        color='Species'244    ).properties(245        title=f"{y_feature.value} vs {x_feature.value}",246        width=500,247        height=400248    )249 250    chart251    return252 253```254</example>255 256<example title="Conditional Outputs">257```258 259@app.cell260def _():261    mo.stop(not data.value, mo.md("No data to display"))262 263    if mode.value == "scatter":264        mo.output.replace(render_scatter(data.value))265    else:266        mo.output.replace(render_bar_chart(data.value))267    return268 269```270</example>271 272<example title="Interactive chart with Altair">273```274 275@app.cell276def _():277    import marimo as mo278    import altair as alt279    import polars as pl280    return281 282@app.cell283def _():284    # Load dataset285    weather = pl.read_csv("<https://raw.githubusercontent.com/vega/vega-datasets/refs/heads/main/data/weather.csv>")286    weather_dates = weather.with_columns(287        pl.col("date").str.strptime(pl.Date, format="%Y-%m-%d")288    )289    _chart = (290        alt.Chart(weather_dates)291        .mark_point()292        .encode(293            x="date:T",294            y="temp_max",295            color="location",296        )297    )298    return299 300@app.cell301def _():302    chart = mo.ui.altair_chart(_chart)303chart304    return305 306@app.cell307def _():308    # Display the selection309    chart.value310    return311 312```313</example>314 315<example title="Run Button Example">316```317 318@app.cell319def _():320    import marimo as mo321    return322 323@app.cell324def _():325    first_button = mo.ui.run_button(label="Option 1")326    second_button = mo.ui.run_button(label="Option 2")327    [first_button, second_button]328    return329 330@app.cell331def _():332    if first_button.value:333        print("You chose option 1!")334    elif second_button.value:335        print("You chose option 2!")336    else:337        print("Click a button!")338    return339 340```341</example>342 343<example title="SQL with duckdb">344```345 346@app.cell347def _():348    import marimo as mo349    import polars as pl350    return351 352@app.cell353def _():354    weather = pl.read_csv('<https://raw.githubusercontent.com/vega/vega-datasets/refs/heads/main/data/weather.csv>')355    return356 357@app.cell358def _():359    seattle_weather_df = mo.sql(360        f"""361        SELECT * FROM weather WHERE location = 'Seattle';362        """363    )364    return365 366```367</example>368