My Streamlit Love Affair: Simple Slider Interactivity With GPT4 Prompting
Prompt engineering for interactive Python single and dual slider Streamlit maps
Interactive choropleth maps are powerful tools for visualizing and understanding complex datasets related to geographical areas.
Streamlit turns Python scripts into shareable web apps in minutes, no front-end experience required.
For data scientists and developers looking to provide interactivity for their users, Streamlit is the Python framework that can easily provide it.
A useful interactive feature with data over time is the Streamlit slider feature.
To simplify coding even more, if we have a data set that we want to use, we can prompt GPT-4 to generate the Python code for us.
Here are two choropleth map examples that implement a:
single slider for yearly global choropleth map visualization
dual slider for year range global choropleth map visualization
Example 1: Time Slider for Yearly Data Visualization
For our first example, let’s create a choropleth map that uses a slider to navigate through yearly UN Global Peace Index (GPI) data.
This dataset can be downloaded from the website visionofhumanity.org. The GPI contains a numerical value indicating the relative peacefulness of 163 countries over a 15 year period (2008–2022).
This allows users to see how peace levels in different countries have evolved over time. Once we have downloaded the file, we can save it (I saved mine as global_peace_index.csv)
This is a perfect dataset to use for creating a global choropleth map!
And Streamlit has an interactive slider widget that the user can “drag” to show the changes from year to year.
To greatly simplify the process of turning this dataset into an interactive visual, we can use GPT-4. The first step is to upload the file to our GPT-4 chat window:
Once GPT-4 has an idea of the fields in the dataset, we can prompt to generate our Python visualization code.
Prompt to GPT-4: Please generate the Python Streamlit code to create an interactive choropleth map with a slider for changing the year. The map should display the Global Peace Index by country for each year using the provided dataset.
Response from GPT-4:
import pandas as pd
import streamlit as st
import plotly.express as px
# Load the dataset
data = pd.read_csv('global_peace_index.csv')
# Convert wide format to long format
data_long = data.melt(id_vars=["Country", "iso3c"],
var_name="Year",
value_name="Peace_Index")
# Slider for selecting the year
years = data_long['Year'].unique()
year_selected = st.slider('Select a Year', min_value=int(min(years)), max_value=int(max(years)), value=int(max(years)))
# Filter data based on the selected year
data_filtered = data_long[data_long['Year'] == str(year_selected)]
# Creating the choropleth map
fig = px.choropleth(data_filtered, locations="iso3c",
color="Peace_Index",
hover_name="Country",
color_continuous_scale=px.colors.sequential.Plasma,
title=f"Global Peace Index - {year_selected}")
st.plotly_chart(fig)
To run the code, we need to access a terminal prompt. For my example, I am using the PyCharm IDE. I can open a prompt window within the IDE and can run the code from there:
The resulting interactive map (displayed in the default browser window) with a fully-functional slider by year:
Awesome!
This shows us the situation for each country by year — but what about if we want to see if a country is becoming more or less peaceful over a range of years?
Streamlit has the perfect solution for us! A dual slider!
Can we prompt GPT-4 to create this code for us? Let’s give it a try.
Example 2: Dual Slider for Year Range Comparisons
For this second interactive visualization example, we want to allow users to compare the Global Peace Index between two selected years. In other words, we want to let them select a range of years.
The Streamlit dual slider functionality enables comparison of start and end years.
Now to accurately represent changes in peace levels, we want our map to visualize increases in peace (positive change) and decreases in peace (negative change) with a centered color scale.
And we want the map to show improvements in peace on a green scale, and deteriorations of peace on a red scale.
Prompt to GPT-4: Using the same dataset, create an interactive choropleth map allowing users to compare the Global Peace Index scores of countries between two selected years. Include a dual-year slider for users to select the start and end years for comparison. The map should visualize the change in Peace Index scores between these years, highlighting improvements (in green) or deteriorations (in red) in global peace. Please use Plotly for the map visualization
Response from GPT-4:
import pandas as pd
import streamlit as st
import plotly.express as px
# Load the dataset
data = pd.read_csv('global_peace_index.csv')
# Convert the dataset from wide to long format
data_long = pd.melt(data, id_vars=['Country', 'iso3c'], var_name='Year', value_name='Peace_Index')
# Selecting the start and end year for comparison
start_year, end_year = st.select_slider('Select Year Range for Comparison', options=sorted(data_long['Year'].unique()), value=(sorted(data_long['Year'].unique())[0], sorted(data_long['Year'].unique())[-1]))
# Filtering the dataset for the selected years
data_start = data_long[data_long['Year'] == start_year]
data_end = data_long[data_long['Year'] == end_year]
# Merging the datasets to compare
data_merged = data_start[['Country', 'iso3c', 'Peace_Index']].merge(data_end[['Country', 'iso3c', 'Peace_Index']], on=['Country', 'iso3c'], suffixes=('_start', '_end'))
data_merged['Change'] = data_merged['Peace_Index_end'] - data_merged['Peace_Index_start']
# Creating the choropleth map to show the change in Peace Index
fig = px.choropleth(data_merged, locations='iso3c', color='Change', hover_name='Country', color_continuous_scale=px.colors.diverging.RdYlGn, title='Change in Global Peace Index')
st.plotly_chart(fig)
OK, that is terrific. Does the code work? We can copy/paste into our Python editor (for me it is Pycharm) and Save as a .py file.
Again, to run the file (from the PyCharm terminal window):
And the resulting interactive dual slider choropleth map visualization displayed in the default browser):
As you can see, we can move the slider at both ends allowing us more flexibility to emphasize areas that have become more peaceful versus those that have become less peaceful over a period of time.
Our example shows that between 2016 and 2020, a number of countries stand out as having become less safe — Venezuela, Iran, Afghanistan, Yemen, and Niger being a few of them.
And we created this amazing visualization in 10 minutes with GPT-4 — all we needed to provide was a CSV data file and a carefully-crafted prompt.
Super simple, super fast, superb Streamlit visuals.
In Summary…
With GPT-4 we can create fully functional Streamlit code from a single prompt — from data in a raw CSV file to an interactive choropleth map — just like that.
By integrating sliders (single AND dual), these maps can become even more interactive, allowing users to explore different dimensions of the data, such as time, categories, or any quantitative metric.
Whether you are a beginner just learning how to use the Streamlit framework or an experienced coder wanting to implement more advanced interfaces, the GPT-4 Code Interpreter is a handy tool.
Even as a 20-year comp sci professional, I regularly include it as part of my Streamlit professional development workflow.
Thank you for reading.
If you want to learn more about how to prompt engineer GPT-4, sign up for this free 5-day email course on Prompting GPT-4 for data visuals. Let me know what you think: