CoolFace
Apppublic

marimo-team/marimo-learn

sourceHugging Faceupdated 5mo agoView on Hugging Face
3likes
08_debugging.py370 linesDownload Raw Back to altair
1# /// script2# requires-python = ">=3.11"3# dependencies = [4#     "altair==6.1.0",5#     "marimo",6#     "pandas==3.0.1",7# ]8# ///9 10import marimo11 12__generated_with = "0.20.4"13app = marimo.App()14 15 16@app.cell17def _():18    import marimo as mo19 20    return (mo,)21 22 23@app.cell(hide_code=True)24def _(mo):25    mo.md(r"""26    # Altair Debugging Guide27 28    In this notebook we show you common debugging techniques that you can use if you run into issues with Altair.29 30    You can jump to the following sections:31 32    * [Installation and Setup](#Installation) when Altair is not installed correctly33    * [Display Issues](#Display-Troubleshooting) when you don't see a chart34    * [Invalid Specifications](#Invalid-Specifications) when you get an error35    * [Properties are Being Ignored](#Properties-are-Being-Ignored) when you don't see any errors or warnings36    * [Asking for Help](#Asking-for-Help) when you get stuck37    * [Reporting Issues](#Reporting-Issues) when you find a bug38 39    In addition to this notebook, you might find the [Frequently Asked Questions](https://altair-viz.github.io/user_guide/faq.html) and [Display Troubleshooting](https://altair-viz.github.io/user_guide/troubleshooting.html) guides helpful.40 41    _This notebook is part of the [data visualization curriculum](https://github.com/uwdata/visualization-curriculum)._42    """)43    return44 45 46@app.cell(hide_code=True)47def _(mo):48    mo.md(r"""49    ## Installation50    """)51    return52 53 54@app.cell(hide_code=True)55def _(mo):56    mo.md(r"""57    These instructions follow [the Altair documentation](https://altair-viz.github.io/getting_started/installation.html) but focus on some specifics for this series of notebooks.58 59    In every notebook, we will import the [Altair](https://github.com/altair-viz/altair) package. If you are running this notebook on [Colab](https://colab.research.google.com), Altair should be preinstalled and ready to go. The notebooks in this series are designed for Colab but should also work in Jupyter Lab or the Jupyter Notebook (the notebook requires a bit more setup [described below](#Special-Setup-for-the-Jupyter-Notebook)) but additional packages are required.60 61    If you are running in Jupyter Lab or Jupyter Notebooks, you have to install the necessary packages by running the following command in your terminal.62 63    ```bash64    pip install altair65    ```66 67    Or if you use [Conda](https://conda.io)68 69    ```bash70    conda install -c conda-forge altair71    ```72 73    You can run command line commands from a code cell by prefixing it with `!`. For example, to install Altair and Vega Datasets with [Pip](https://pip.pypa.io/), you can run the following cell.74    """)75    return76 77 78@app.cell79def _():80    # packages added via marimo's package management: altair !pip install altair81    return82 83 84@app.cell85def _():86    import altair as alt87    import pandas as pd88 89    return alt, pd90 91 92@app.cell(hide_code=True)93def _(mo):94    mo.md(r"""95    ### Make sure you are Using the Latest Version of Altair96    """)97    return98 99 100@app.cell(hide_code=True)101def _(mo):102    mo.md(r"""103    If you are running into issues with Altair, first make sure that you are running the latest version. To check the version of Altair that you have installed, run the cell below.104    """)105    return106 107 108@app.cell109def _(alt):110    alt.__version__111    return112 113 114@app.cell(hide_code=True)115def _(mo):116    mo.md(r"""117    To check what the latest version of altair is, go to [this page](https://pypi.org/project/altair/) or run the cell below (requires Python 3).118    """)119    return120 121 122@app.cell123def _():124    import urllib.request, json 125    with urllib.request.urlopen("https://pypi.org/pypi/altair/json") as url:126        print(json.loads(url.read().decode())['info']['version'])127    return128 129 130@app.cell(hide_code=True)131def _(mo):132    mo.md(r"""133    If you are not running the latest version, you can update it with `pip`. You can update Altair and Vega Datasets by running this command in your terminal.134 135    ```136    pip install -U altair137    ```138    """)139    return140 141 142@app.cell(hide_code=True)143def _(mo):144    mo.md(r"""145    ### Try Making a Chart146    """)147    return148 149 150@app.cell(hide_code=True)151def _(mo):152    mo.md(r"""153    Now you can create an Altair chart.154    """)155    return156 157 158@app.cell159def _(alt, pd):160    cars = pd.read_json("https://cdn.jsdelivr.net/npm/vega-datasets@2/data/cars.json")161 162    alt.Chart(cars).mark_point().encode(163        x='Horsepower',164        y='Displacement',165        color='Origin'166    )167    return (cars,)168 169 170@app.cell(hide_code=True)171def _(mo):172    mo.md(r"""173    ### Special Setup for the Jupyter Notebook174    """)175    return176 177 178@app.cell(hide_code=True)179def _(mo):180    mo.md(r"""181    If you are running in Jupyter Lab, Jupyter Notebook, or Colab (and have a working Internet connection) you should be seeing a chart. If you are running in another environment (or offline), you will need to tell Altair to use a different renderer;182 183    To activate a different renderer in a notebook cell:184 185    ```python186    # to run in nteract, VSCode, or offline in JupyterLab187    alt.renderers.enable('mimebundle')188 189    ```190 191    To run offline in Jupyter Notebook you must install an additional dependency, the `vega` package. Run this command in your terminal:192 193    ```bash194    pip install vega195    ```196 197    Then activate the notebook renderer:198 199    ```python200    # to run offline in Jupyter Notebook201    alt.renderers.enable('notebook')202 203    ```204 205 206    These instruction follow [the instructions on the Altair website](https://altair-viz.github.io/getting_started/installation.html#installation-notebook).207    """)208    return209 210 211@app.cell(hide_code=True)212def _(mo):213    mo.md(r"""214    ## Display Troubleshooting215 216    If you are having issues with seeing a chart, make sure your setup is correct by following the [debugging instruction above](#Installation). If you are still having issues, follow the [instruction about debugging display issues in the Altair documentation](https://iliatimofeev.github.io/altair-viz.github.io/user_guide/troubleshooting.html).217    """)218    return219 220 221@app.cell(hide_code=True)222def _(mo):223    mo.md(r"""224    ### Non Existent Fields225 226    A common error is [accidentally using a field that does not exist](https://iliatimofeev.github.io/altair-viz.github.io/user_guide/troubleshooting.html#plot-displays-but-the-content-is-empty).227    """)228    return229 230 231@app.cell232def _(alt):233    import pandas as pd234 235    df = pd.DataFrame({'x': [1, 2, 3],236                         'y': [3, 1, 4]})237 238    alt.Chart(df).mark_point().encode(239        x='x:Q',240        y='y:Q',241        color='color:Q'  # <-- this field does not exist in the data!242    )243    return (df,)244 245 246@app.cell(hide_code=True)247def _(mo):248    mo.md(r"""249    Check the spelling of your files and print the data source to confirm that the data and fields exist. For instance, here you see that `color` is not a valid field.250    """)251    return252 253 254@app.cell255def _(df):256    df.head()257    return258 259 260@app.cell(hide_code=True)261def _(mo):262    mo.md(r"""263    ## Invalid Specifications264 265    Another common issue is creating an invalid specification and getting an error.266    """)267    return268 269 270@app.cell(hide_code=True)271def _(mo):272    mo.md(r"""273    ### Invalid Properties274 275    Altair might show an `SchemaValidationError` or `ValueError`. Read the error message carefully. Usually it will tell you what is going wrong.276    """)277    return278 279 280@app.cell(hide_code=True)281def _(mo):282    mo.md(r"""283    For example, if you forget the mark type, you will see this `SchemaValidationError`.284    """)285    return286 287 288@app.cell289def _(alt, cars):290    alt.Chart(cars).encode(291        y='Horsepower'292    )293    return294 295 296@app.cell(hide_code=True)297def _(mo):298    mo.md(r"""299    Or if you use a non-existent channel, you get a `TypeError`.300    """)301    return302 303 304@app.cell305def _(alt, cars):306    try:307        alt.Chart(cars).mark_point().encode(308            z='Horsepower'309        )310    except TypeError as e:311        print(f"TypeError: {e}")312    return313 314 315@app.cell(hide_code=True)316def _(mo):317    mo.md(r"""318    ## Properties are Being Ignored319 320    Altair might ignore a property that you specified. In the chart below, we are using a `text` channel, which is only compatible with `mark_text`. You do not see an error or a warning about this in the notebook. However, the underlying Vega-Lite library will show a warning in the browser console.  Press <kbd>Alt</kbd>+<kbd>Cmd</kbd>+<kbd>I</kbd> on Mac or <kbd>Alt</kbd>+<kbd>Ctrl</kbd>+<kbd>I</kbd> on Windows and Linux to open the developer tools and click on the `Console` tab. When you run the example in the cell below, you will see a the following warning.321 322    ```323    WARN text dropped as it is incompatible with "bar".324    ```325    """)326    return327 328 329@app.cell330def _(alt, cars):331    alt.Chart(cars).mark_bar().encode(332        y='mean(Horsepower)',333        text='mean(Acceleration)'334    )335    return336 337 338@app.cell(hide_code=True)339def _(mo):340    mo.md(r"""341    If you find yourself debugging issues related to Vega-Lite, you can open the chart in the [Vega Editor](https://vega.github.io/editor/) either by clicking on the "Open in Vega Editor" link at the bottom of the chart or in the action menu (click to open) at the top right of a chart. The Vega Editor provides additional debugging but you will be writing Vega-Lite JSON instead of Altair in Python.342 343    **Note**: The Vega Editor may be using a newer version of Vega-Lite and so the behavior may vary.344    """)345    return346 347 348@app.cell(hide_code=True)349def _(mo):350    mo.md(r"""351    ## Asking for Help352 353    If you find a problem with Altair and get stuck, you can ask a question on Stack Overflow. Ask your question with the `altair` and `vega-lite` tags. You can find a list of questions people have asked before [here](https://stackoverflow.com/questions/tagged/altair).354    """)355    return356 357 358@app.cell(hide_code=True)359def _(mo):360    mo.md(r"""361    ## Reporting Issues362 363    If you find a problem with Altair and believe it is a bug, please [create an issue in the Altair GitHub repo](https://github.com/altair-viz/altair/issues/new) with a description of your problem. If you believe the issue is related to the underlying Vega-Lite library, please [create an issue in the Vega-Lite GitHub repo](https://github.com/vega/vega-lite/issues/new).364    """)365    return366 367 368if __name__ == "__main__":369    app.run()370