
Image by Author | Ideogram
# Introduction
Data has become a vital resource for any business, as it provides a means for companies to gain valuable insights, particularly when making decisions. Without data, decisions rely solely on instinct and luck, which is not the most effective approach.
However, vast amounts of raw data are difficult to understand. It provides no direct insights and requires further processing. This is why many people rely on using data dashboards to summarize, visualize, and navigate the raw data we have. By developing a sleek dashboard, we can provide a straightforward way for non-technical users to easily gain insights from data.
That’s why this article will explore how to create a sleek data dashboard by leveraging Python, Taipy, and Google Sheets.
Let’s get into it.
# Developing a Slick Data Dashboard
We will start the tutorial by preparing all the necessary credentials to access Google Sheets via Python. First, create a Google account and navigate to the Google Cloud Console. Then, navigate to APIs & Services > Library, where you need to enable the Google Sheets API and Google Drive API.
After enabling the APIs, return to APIs & Services > Credentials and navigate to Create Credential > Service Account. Follow the directions and assign the role, such as Editor or Owner, so that we can read and write to Google Sheets. Select the service account we just created, then navigate to Keys > Add Key > Create New Key. Select JSON and download the credentials.json
file. Store it somewhere and open the file; then, copy the email value under client_email
.
For the dataset, we will use the cardiac dataset from Kaggle as an example. Store the file in Google Drive and open it as Google Sheets. In the Google Sheets file, go to the File > Share button and add the email you just copied. Lastly, copy the URL for the Google Sheets file, as we will access the data later via the URL.
Open your favorite IDE, and then we will structure our project as follows:
taipy_gsheet/
│
├── config/
│ └── credentials.json
├── app.py
└── requirements.txt
Create all the necessary files, and then we will start developing our dashboard. We will be using Taipy for the application framework, pandas for data manipulation, gspread and oauth2client for interacting with the Google Sheets API, and plotly for creating visualizations. In the requirements.txt
file, add the following packages:
taipy
pandas
gspread
oauth2client
plotly
These are the necessary libraries for our tutorial, and we will install them in our environment. Don’t forget to use a virtual environment to prevent breaking your main environment. We will also use Python 3.12; as of the time this article was written, this is the Python version that currently works for the libraries above.
Install the libraries using the following command:
pip install -r requirements.txt
If the installation is successful, then we will prepare our application. In app.py
, we will build the code to set up our dashboard.
First, we will import all the necessary libraries that we will use for developing the application.
import pandas as pd
import gspread
import plotly.express as px
import taipy as tp
from taipy import Config
from taipy.gui import Gui
import taipy.gui.builder as tgb
Next, we will load the data from Google Sheets using the following code. Change the SHEET_URL
value with your actual data URL. Additionally, we will preprocess the data to ensure it works well.
SHEET_URL = "https://docs.google.com/spreadsheets/d/1Z4S3hnV3710OJi4yu5IG0ZB5w0q4pmNPKeYy8BTyM8A/"
client = gspread.service_account(filename="config/credentials.json")
df_raw = pd.DataFrame(client.open_by_url(SHEET_URL).get_worksheet(0).get_all_records())
df_raw["sex"] = pd.to_numeric(df_raw["sex"], errors="coerce").fillna(0).astype(int)
df_raw["sex_label"] = df_raw["sex"].map({0: "Female", 1: "Male"})
Then, we will prepare the dashboard with Taipy. Taipy is an open-source library for data-driven applications, covering both front-end and back-end development. Let’s use the library to build the data dashboard with the basic features we can use with Taipy.
In the code below, we will develop a scenario, which is a pipeline that the user can execute for what-if analysis. It’s essentially a framework for experimenting with various parameters that we can pass to the pipeline. For example, here is how we prepare a scenario for the average age with the input of the gender filter.
def compute_avg_age(filtered_df: pd.DataFrame, gender_filter: str) -> float:
data = (
filtered_df
if gender_filter == "All"
else filtered_df[filtered_df["sex_label"] == gender_filter]
)
return round(data["age"].mean(), 1) if not data.empty else 0
filtered_df_cfg = Config.configure_data_node("filtered_df")
gender_filter_cfg = Config.configure_data_node("gender_filter")
avg_age_cfg = Config.configure_data_node("avg_age")
task_cfg = Config.configure_task(
"compute_avg_age", compute_avg_age, [filtered_df_cfg, gender_filter_cfg], avg_age_cfg
)
scenario_cfg = Config.configure_scenario("cardiac_scenario", [task_cfg])
Config.export("config.toml")
We will revisit the scenario later, but let’s prepare the gender selection itself and its default state.
gender_lov = ["All", "Male", "Female"]
gender_selected = "All"
filtered_df = df_raw.copy()
pie_fig = px.pie()
box_fig = px.box()
avg_age = 0
Next, we will create the functions that update our variables and data visualizations when a user interacts with the dashboard, such as by selecting a gender or submitting a scenario.
def update_dash(state):
subset = (
df_raw if state.gender_selected == "All"
else df_raw[df_raw["sex_label"] == state.gender_selected]
)
state.filtered_df = subset
state.avg_age = round(subset["age"].mean(), 1) if not subset.empty else 0
state.pie_fig = px.pie(
subset.groupby("sex_label")["target"].count().reset_index(name="count"),
names="sex_label", values="count",
title=f"Target Count -- {state.gender_selected}"
)
state.box_fig = px.box(subset, x="sex_label", y="chol", title="Cholesterol by Gender")
def save_scenario(state):
state.scenario.filtered_df.write(state.filtered_df)
state.scenario.gender_filter.write(state.gender_selected)
state.refresh("scenario")
tp.gui.notify(state, "s", "Scenario saved -- submit to compute!")
With the functions ready, we will prepare the front-end dashboard with a basic composition with the code below:
with tgb.Page() as page:
tgb.text("# Cardiac Arrest Dashboard")
tgb.selector(value="{gender_selected}", lov="{gender_lov}",
label="Select Gender:", on_change=update_dash)
with tgb.layout(columns="1 1", gap="20px"):
tgb.chart(figure="{pie_fig}")
tgb.chart(figure="{box_fig}")
tgb.text("### Average Age (Live): {avg_age}")
tgb.table(data="{filtered_df}", pagination=True)
tgb.text("---")
tgb.text("## Scenario Management")
tgb.scenario_selector("{scenario}")
tgb.selector(label="Scenario Gender:", lov="{gender_lov}",
value="{gender_selected}", on_change=save_scenario)
tgb.scenario("{scenario}")
tgb.scenario_dag("{scenario}")
tgb.text("**Avg Age (Scenario):**")
tgb.data_node("{scenario.avg_age}")
tgb.table(data="{filtered_df}", pagination=True)
The dashboard above is simple, but it will change according to the selections we make.
Lastly, we will prepare the orchestration process with the following code:
if __name__ == "__main__":
tp.Orchestrator().run()
scenario = tp.create_scenario(scenario_cfg)
scenario.filtered_df.write(df_raw)
scenario.gender_filter.write("All")
Gui(page).run(title="Cardiac Arrest Dashboard", dark_mode=True)
Once you have the code ready, we will run the dashboard with the following command:
Automatically, the dashboard will show up in your browser. For example, here is a simple cardiac arrest dashboard with the visualizations and the gender selection.
If you are scrolling down, here is how the scenario pipeline is shown. You can try to select the gender and submit the scenario to see the differences in the average age.
That’s how you can build a slick data dashboard with just a few components. Explore the Taipy documentation to add visualizations and features that are suitable for your dashboard needs.
# Wrapping Up
Data is a resource that every company needs, but gaining insights from the data is more difficult if it is not visualized. In this article, we have created a sleek data dashboard using Python, Taipy, and Google Sheets. We demonstrated how to connect to data from Google Sheets and utilize the Taipy library to construct an interactive dashboard.
I hope this has helped!
Cornellius Yudha Wijaya is a data science assistant manager and data writer. While working full-time at Allianz Indonesia, he loves to share Python and data tips via social media and writing media. Cornellius writes on a variety of AI and machine learning topics.