|

PyScript for Data Science: How to Use Pandas & Matplotlib in HTML

3D isometric illustration of Python data charts and Pandas grids rendering directly inside a web browser window using PyScript.

You’ve learned how PyScript can run Python in a browser and how to interact with the page. Now, let’s do something powerful. In this article, we’ll look at how PyScript integrates Pandas and Matplotlib to supercharge your browser-based data analysis.

What if you could build a data dashboard that runs entirely in the browser, using the tools you already know? No server, no Flask, no Django.

Step 1: The <py-env> Tag

Before we can use libraries like Pandas or Matplotlib, we have to tell PyScript to download them. We do this with the <py-env> tag in the <head> of our HTML.

<head>
  <link rel="stylesheet" href="https.pyscript.net/latest/pyscript.css" />
  <script defer src="https.pyscript.net/latest/pyscript.js"></script>
  
  <py-env>
    - pandas
    - matplotlib
  </py-env>
</head>

(This may take a moment to load the first time, as it’s pulling the libraries.)

Step 2: Running Pandas in the Browser

Let’s read some data, analyze it with Pandas, and write the result to the page.

<body>
  <h1>Pandas in the Browser!</h1>
  <p>Here is the head of our DataFrame:</p>
  <div id="df-output"></div>

  <py-script output="df-output">
    import pandas as pd
    
    # Create a simple DataFrame
    data = {
        'Product': ['A', 'B', 'A', 'C', 'B'],
        'Sales': [100, 150, 200, 50, 120]
    }
    df = pd.DataFrame(data)
    
    # Analyze it!
    product_sales = df.groupby('Product')['Sales'].sum()
    
    # Display the result
    product_sales
  </py-script>
</body>

When you load this page, PyScript will execute the Pandas code and “print” the resulting DataFrame to the df-output div.

Step 3: Plotting with Matplotlib

This is the “wow” moment. Let’s create a bar chart of our results and display it on the page.

<body>
  <h1>Matplotlib in the Browser!</h1>
  <div id="plot"></div> <py-script output="plot">
    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = {
        'Product': ['A', 'B', 'A', 'C', 'B'],
        'Sales': [100, 150, 200, 50, 120]
    }
    df = pd.DataFrame(data)
    product_sales = df.groupby('Product')['Sales'].sum()
    
    # Create the plot
    fig, ax = plt.subplots()
    product_sales.plot(kind='bar', ax=ax, title="Total Sales by Product")
    
    # The last line is what PyScript shows
    fig
  </py-script>
</body>

You now have a fully interactive, Python-powered dashboard running 100% in the user’s browser. This is the future of lightweight data apps.

Similar Posts

Leave a Reply