Creating Python Surveys: A Beginner's Guide to Shiny for Python

Hello, fellow Python enthusiasts! Today we have a really exciting topic for you. If you're like me, you've probably thought to yourself, "I wonder if I could create a survey myself?" In today's post, we'll make that dream a reality!

We'll be using a powerful tool called 'Shiny for Python', and as we dive into the ins and outs of using it, we'll create our own awesome survey app. If you're a beginner, don't worry, this post is for you!

So, let's take a trip into the magical world of Python together. Let's get started by creating a Python survey that will let your creativity run wild!

1. Shiny for Python: New Horizons for Surveys

Shiny for Pythonis a framework that is rapidly gaining popularity among data scientists and developers. Why? Because it allows you to create interactive web applications without the need for complex web technologies.

Especially when building a survey app, Shiny for Python is a great way to go from data collection to analysis in one step.

Shiny for Python

Shiny for Python is a framework that enables you to develop responsive web applications in Python. It brings the popular Shiny package from the R language to the Python environment, enabling data scientists to create interactive data visualization apps without the need for complex web development knowledge.
Shiny for Python consists of a UI and a server part, which can dynamically calculate and display results based on user input. It also provides the ability to run apps directly in the browser without a server via Shinylive.

2. Before you begin: What to bring checklist

Before you start building your Python survey app, you'll need a few things. Let's check them out together.

  1. Python 3.8 or later. (You can check this version using the Click here)
  2. Your favorite code editor (e.g., VS Code, PyCharm)
  3. Basic knowledge of terminal usage
  4. Passion and curiosity (most important!)

Okay, now that we're all set up, let's get excited!

3. Install Shiny for Python

First, you need to install Shiny for Python. Open a terminal and type the following command

pip install shiny

Running the above command will simply install Shiny for Python, the first step in creating a Python survey. Cool, right? (Below, I'm running a reinstall with it already installed, so you can see I'm already satisfied).

Shiny for Python 설치하기
(Shiny for Python installation terminal image)

4. Create your first Shiny app

Let's dive into creating a Python survey. First, let's start with the most basic of Shiny apps, which you may recognize as the Virtual Environmentsto run the code below.

#survey_app

from shiny import App, ui

Define the # UI
app_ui = ui.page_fluid(
    ui.h1("My First Shiny App"),
    ui.p("Welcome to the world of Shiny for Python!")
)

# Empty server function (you can add logic later)
def server(input, output, session):
    pass

Create a # Shiny app object
app = App(app_ui, server)

Code commentary

  • (I saved the code above with the name survey_app).
  • from shiny import App, ui: Fetch the necessary classes and modules from the Shiny library.
  • app_ui = ui.page_fluid(...)Defines the user interface (UI) of the application.
    • ui.h1(...): Add a large heading (H1 tag) to the page.
    • ui.p(...)Add a : paragraph (p tag) to display the welcome message.
  • def server(input, output, session):Defines a server function. This is currently an empty function, but you can add your application's logic here in the future1.
  • app = App(app_ui, server): Combines UI and server functions to create a Shiny application object.
shiny run survey_app.py

If you type the above command into the terminal and press Enter, you should get the following response: 127.0.0.1:8000, which, when clicked while holding down the Ctrl key, generates a really simple web page. Fascinating, isn't it?

코드창과 터미널 이미지
(Image of PyCharm code window and terminal window)
생성된 웹페이지 이미지
(Web page image generated by running a shiny app)

5. Create a survey form

Now let's get down to business and create a survey form. We'll create a simple form that asks for your name, age, and favorite programming language.

from shiny import App, ui, reactive

Define the # UI
app_ui = ui.page_fluid(
    ui.h1("Python Programmer Survey"), # title (h1 tag)
    ui.input_text("name", "Enter your name"), # Text input field (name)
    ui.input_numeric("age", "Enter your age", value=20), # Numeric input field (default 20)
    ui.input_select(
        "fav_lang",
        "What is your favorite programming language?", # select input field
        choices=["Python", "JavaScript", "Java", "C++", "Other"]
    ),
    ui.input_action_button("submit", "Submit"), # button (Submit)
    ui.output_text_verbatim("result") # output field (result)
)

Define the # server logic
def server(input, output, session):
    @reactive.Effect
    @reactive.event(input.submit) # Execute on button click
    def submit_survey():
        # Combines the input data into a string and outputs it
        result = f"Name: {input.name()}, Age: {input.age()}, Favorite Language: {input.fav_lang()}"
        output.result.set(result) # Display the result in the UI

Run the # Shiny app
app = App(app_ui, server)

Code commentary

  • UI configuration (app_ui)
    • ui.h1(...) : Displays the title of the survey.
    • ui.input_text(...) : Provide a text field for the user to enter a name.
    • ui.input_numeric(...) : Provides a numeric field for you to enter your age. The default value is 20.
    • ui.input_select(...) Create a drop-down menu so users can select their favorite programming language.
    • ui.input_action_button(...) : Add a Submit Survey button.
    • ui.output_text_verbatim(...) : Creates a space to output the result of the user's input as text.
  • Server logic (server function)
    • @reactive.Effect : Specifies it as a responsive function.
    • @reactive.event(input.submit) Click the : button (submit) It only runs when the event occurs.
    • result = f"Name: {input.name()}, Age: {input.age()}, Favorite Language: {input.fav_lang()}"
      → Take the data entered by the user and generate a string.
    • output.result.set(result)
      → Save the result to the output_text_verbatim("result") area of the page.
  • Run the Shiny app (app = App(app_ui, server))
    • App(app_ui, server)to connect the UI to the server.
    • app.run()opens the app in a web browser.

This will result in a basic Python survey form like the one below. Isn't that pretty cool?

파이썬 설문조사 폼 웹페이지

6. Save the data

Collecting and storing data is key to surveys. Let's add the ability to store survey respondents' data in a CSV file.

from shiny import App, ui, reactive
import pandas as pd # Install those packages with pip install pandas if needed
from pathlib import Path

Define the # UI
app_ui = ui.page_fluid(
    ui.h1("Python Programmer Survey"), # title (h1 tag)
    ui.input_text("name", "Enter your name"), # Text input field (name)
    ui.input_numeric("age", "Enter your age", value=20), # Numeric input field (default 20)
    ui.input_select(
        "fav_lang",
        "What is your favorite programming language?", # select input field
        choices=["Python", "JavaScript", "Java", "C++", "Other"]
    ),
    ui.input_action_button("submit", "Submit"), # button (Submit)
    ui.output_text_verbatim("result") # output field (result)
)

Define the # server logic
def server(input, output, session):
    @reactive.Effect
    @reactive.event(input.submit) # Execute on button click
    def submit_survey():
        # Store the data entered by the user in the form of a dictionary
        data = {
            "name": [input.name()],
            "age": [input.age()],
            "favorite_language": [input.fav_lang()]
        }
        
        Convert the # data into a Pandas DataFrame
        df = pd.DataFrame(data)

        Check if the # CSV file exists and save it
        file_path = "survey_results.csv"
        if not Path(file_path).exists():
            df.to_csv(file_path, index=False) # Include headers on first save
        else:
            df.to_csv(file_path, mode="a", header=False, index=False) # Save additional to existing file

        Output the # result message to the UI
        output.result.set("Your response has been recorded. Thank you!")

# Run the Shiny app
app = App(app_ui, server)

Code commentary

1. Saving data to a CSV file

  • The user's input data is stored in a dictionary (dict) format.
  • pandas.DataFrameto convert it to a dataframe.
  • Save the response data to the "survey_results.csv" Save to a file.
    • If it doesn't exist, create a new file and click Save with header.
    • If the file already exists, save the new response data in Append mode (excluding headers).

2. Responsive event handling

  • @reactive.event(input.submit)using the Submit Set to run only when the button is pressed.

3. Display the resulting message

  • After saving the data "Your response has been recorded. Thank you!" Outputs the message to the UI.

In the Python survey form, we entered Trump, age 20, and Python, and when we hit the submit button, the survey responses are now saved in a CSV file (survey_result). If you click on this file, you'll see the data you entered as shown below!

CSV파일로 데이터 저장하기

Congratulations, you've done an amazing job creating a Python survey and taking your first steps into data analysis.

7. Visualize survey results

Now that we've collected our data, let's visualize the results. Let's create a simple chart using Shiny for Python and matplotlib.

from shiny import App, ui, reactive, render
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path

Define the # UI
app_ui = ui.page_fluid(
    ui.h1("Python Programmer Survey"), # title
    ui.input_text("name", "Enter your name"), # name input field
    ui.input_numeric("age", "Enter your age", value=20), # Age input field
    ui.input_select(
        "fav_lang",
        "What is your favorite programming language?", # Select favorite programming language
        choices=["Python", "JavaScript", "Java", "C++", "Other"]
    ),
    ui.input_action_button("submit", "Submit"), # Submit button
    ui.output_text_verbatim("result"), # Result output
    ui.output_plot("age_histogram") # Age distribution histogram output
)

Define the # server logic
def server(input, output, session):
    @reactive.Effect
    @reactive.event(input.submit) # Execute on button click
    def submit_survey():
        # Save user input data as a dictionary
        data = {
            "name": [input.name()],
            "age": [input.age()],
            "favorite_language": [input.fav_lang()]
        }
        
        Convert the # data to a DataFrame
        df = pd.DataFrame(data)

        Set the # file path
        file_path = "survey_results.csv"

        If # CSV file does not exist, create it including headers, if it does, append it (Append)
        if not Path(file_path).exists():
            df.to_csv(file_path, index=False)
        else:
            df.to_csv(file_path, mode="a", header=False, index=False)

        Output the # save complete message
        output.result.set("Your response has been recorded. Thank you!")

    @output
    @render.plot
    def age_histogram():
        Load # survey data
        file_path = "survey_results.csv"
        if not Path(file_path).exists():
            return # Do not plot graph if no data exists

        df = pd.read_csv(file_path)

        Create a histogram of the # age distribution
        fig, ax = plt.subplots(figsize=(10, 6)) # Create a new figure
        ax.hist(df['age'], bins=10, edgecolor='black', alpha=0.7) # Histogram
        ax.set_title('Age Distribution')
        ax.set_xlabel('Age')
        ax.set_ylabel('Response Count')

        return fig # return `fig` instead of `plt.gcf()` return fig

# Run the Shiny app
app = App(app_ui, server)

Code commentary

1. Age distribution histogram (age_histogram Add)

  • ui.output_plot("age_histogram")to make room for the graph in the UI.
  • @output @render.plot Decorator to use the age_histogram() Define a function.
  • survey_results.csvby fetching data from matplotlibto generate a histogram.
  • Age (age) Visualize the number of responses based on the field.

2. Handling exceptions when no data is available

  • if not Path(file_path).exists(): return Add a condition to suppress the graph if there is no survey data.

3. UI updates

  • ui.output_plot("age_histogram")to visualize the age distribution of respondents in real-time.

This creates a histogram that shows the age distribution of the respondents at a glance. Doesn't it make the data come alive? (Right now, I only have four random inputs, so I'm not getting a good histogram).

파이썬 설문조사 만들기
(Image of the live viewable histogram implementation webpage)

8. Wrapping up: The endless possibilities of Shiny for Python

So far, we've used Shiny for Python to create a simple Python survey app, and that's just the beginning! With Shiny for Python, you can create more complex and interactive apps, such as the one below.

  • Dashboards that update in real time
  • Predictive apps with machine learning models
  • Large-scale data visualization tools

Your imagination is the limit!

How did you like creating a Python survey? As you've been learning how to use Shiny for Python, you've noticed how fascinating it is to be able to go from data collection to analysis to visualization all in one go. Now you have the basics to create your own survey app.

If you want to go deeper, Shiny for PythonAnd remember, the best way to learn is to build it yourself. Create your own unique survey app!

Now it's your turn. What cool apps would you like to build with Python and Shiny for Python? Share your ideas in the comments. Let's have fun growing together!

테리 이모티콘
(Happy coding!)

Similar Posts