[Python] Python Shiny Live in Quarto

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    This code below works when doing quarto preview in the terminal. So, the chunk is of type shinylive-python.

    #| standalone: true
    #| layout: vertical
    #| viewerHeight: 250

    from shiny import *

    app_ui = ui.page_fluid(
    ui.input_slider("n", "N", 0, 100, 40),
    ui.output_text_verbatim("txt"),
    ui.output_text_verbatim("txt2")
    )

    def server(input, output, session):
    @output
    @render.text
    def txt():
    return f"The value of n*2 is {input.n() * 2}"

    @render.text
    def txt2():
    return f"The value of n**2 is {input.n() ** 2}"

    app = App(app_ui, server)



    But, I don't know how to read a dataframe and run a plotly off it. For example, a code like this breaks because I'm not sure how to make it read that csv file:

    #| standalone: true
    #| viewerHeight: 420
    #| viewerWidth: 500

    from shiny import App, ui, render
    import pandas as pd
    import plotly.express as px
    from pathlib import Path

    app_ui = ui.page_fluid(
    ui.layout_sidebar(
    ui.sidebar(
    ui.input_slider("cylinder", "Cylinder", 4, 6, 8, step=1)
    ),
    ui.output_plot("plot"),
    ),
    )

    @reactive.calc
    def dat():
    infile = Path(__file__).parent / "exampledf.csv"
    return pd.read_csv(infile)

    def server(input):
    @render.plot(alt="ScatterPlot function")
    def plot():
    file_path= Path(__file__).parent /'exampledf.csv'

    # Load the dataset globally so it can be reused
    df = dat()#pd.read_csv(file_path)

    # Subset the DataFrame using the slider value
    minidf = df[df.cylinders == input.cylinder()].copy()

    # Create a plotly express scatter figure
    fig = px.scatter(
    minidf,
    x="horsepower",
    y="weight",
    title="Scatter Plot of Horsepower vs Weight"
    )
    return fig

    app = App(app_ui, server)




    Any ideas? I basically want to be able to quarto preview this file and run that app inside that chunk in quarto.

    Continue reading...

Compartilhe esta Página