Morph

Code Snippet / Text to Plotly: the easiest way to create a chart interactively

Text to Plotly: the easiest way to create a chart interactively

How to build an AI agent analyzing data using plotly. Text to Plotly is the easiest way to interact with your data.

Code

Python

import pandas as pd
import os
import morph
from morph import MorphGlobalContext
from morph_lib.stream import create_chunk
from morph_lib.ai.openai.code_generation import text_to_plotly

@morph.func
def text_to_plotly_app(context: MorphGlobalContext):
    data = pd.DataFrame({
        "city": [
            "Los Angeles", "San Francisco", "San Diego", "Sacramento",
            "Houston", "Dallas", "Austin", "San Antonio",
            "Miami", "Orlando", "Tampa", "Jacksonville",
            "New York", "Buffalo", "Rochester", "Syracuse",
            "Chicago", "Springfield", "Peoria", "Naperville"
        ],
        "state": [
            "California", "California", "California", "California",
            "Texas", "Texas", "Texas", "Texas",
            "Florida", "Florida", "Florida", "Florida",
            "New York", "New York", "New York", "New York",
            "Illinois", "Illinois", "Illinois", "Illinois"
        ],
        "population": [
            3980400, 883305, 1423851, 508529,
            2328000, 1343000, 964300, 1532200,
            470914, 285713, 399700, 903889,
            8399000, 256304, 206284, 142749,
            2716000, 116250, 112936, 147122
        ]
    })
    prompt = context.vars["prompt"]

    result = text_to_plotly(
        prompt=prompt,
        api_key=os.getenv("OPENAI_API_KEY"),
        df=data,
        model="gpt-4o",
    )
    fig = result.content

    yield create_chunk(f"""Here is python code generated.
```python
{result.code}
```
""", fig.to_html())

    return result

MDX

export const title = "Text to Plotly app"

# Text to Plotly app

<LLM postData="text_to_plotly_app" layout="side-by-side" />

Result

text to plotly