Interactive Python Data Visualization: Adding a Sexy Plotly Range Slider
Implementing a Plotly range slider for added user interactivity

Data visualization is a key aspect of data analysis, and Python provides powerful tools for creating interactive visualizations.
Incorporating interactive components into your visualizations can significantly enhance user engagement.
Let’s take a look at how to add a range slider to your Python data visualizations using Plotly.
For this example, we will be using a cool new dataset offered up by the UN Department of Economic and Social Affairs website (HERE).
Dataset and Preprocessing
The UN dataset for this example models population growth projections by age groups from 2022 to 2100.
The file I selected is under the “Probabilistic Projections” tab and it is called “Population Percentage”.

There are multiple tables in the xlsx file. For this exercise, I selected the “median” table and exported it as a CSV.
After a cursory view, I can see that some data cleaning is in order. The actual data headers start on Row 17. So we can remove the first 16 Rows of data (or just start our data retrieval at this row).
Each row represents a unique combination of country and year, with the columns providing population index figures for various age groups.
Our focus for this example is on the top 10 countries with the highest median population index for the age group “65+”.
Implementing a Range Selector
Range selectors enable dynamic data exploration by allowing users to adjust thresholds or time periods.
To showcase this, let’s create a line plot showing population projections for the ‘65+’ age group for a subset of countries, with a range slider for the year.
Loading the Data and Preprocessing
Before we start with the visualization, we need to load our data and preprocess it to fit our needs.
import pandas as pd
import plotly.graph_objects as go
# Load the dataset
df = pd.read_csv('pp_median_country.csv')
# Convert 'Year' to datetime and '65+' to numeric
df['Year'] = pd.to_datetime(df['Year'], format='%Y')
df['65+'] = pd.to_numeric(df['65+'], errors='coerce')
# Filter rows where 'Year' is between 2022 and 2100
df = df[(df['Year'].dt.year >= 2022) & (df['Year'].dt.year <= 2100)]In this code snippet, we first load the dataset using pandas. We then convert the ‘Year’ column to datetime and the ‘65+’ column to numeric, ensuring the correct data types for our visualization. We also filter the dataframe to only include rows where the ‘Year’ is between 2022 and 2100.
Creating the Initial Plot and Adding Lines
Next, we define a subset of countries that we want to include in our visualization and create a line in our plot for each country in this subset. Each line represents the population projection for the ‘65+’ age group.
# Subset of countries
countries = ['Burundi', 'Kenya', 'Rwanda', 'Uganda', 'Japan', 'Italy', 'Canada']
# Create the initial plot
fig = go.Figure()
# Add a line for each country
for country in countries:
country_data = df[df['Region, subregion, country or area *'] == country]
fig.add_trace(go.Scatter(x=country_data['Year'], y=country_data['65+'], name=country))Adding a Range Slider and Displaying the Plot
Finally, we add a range slider to the x-axis (year) using the rangeslider argument and set the range of the x-axis from 2022 to 2100. This allows users to adjust the year range dynamically. We also set the title of the plot and the labels for the x-axis and y-axis.
# Add a range slider
fig.update_layout(
xaxis=dict(
rangeslider=dict(visible=True),
type='date',
range=['2022', '2100']
),
title='Population Index over the Years for Age Group 65+',
xaxis_title='Year',
yaxis_title='Population Index (%)'
)
# Show the plot
fig.show()And thats all the code you need. Here is an animated image of how the slider works:

As you can see from the animation, you can narrow the Year range in this example — from both sides of the slider. This gives you the ability to focus in more closely, for example, on a specific trend, or anomaly within your data.
Very useful functionality. Nice work!
In Summary…
Adding interactive components like range selectors to your Python data visualizations adds interactivity for your users.
It allows the user to dynamically explore the data within a set range or threshold, providing a more personalized experience.
While we only looked at one type of interactivity in this example, remember that there are many other ways to add interactivity to your visualizations in Python (for example, dropdown menus and toggle buttons).
Check out my other articles for how to do a dropdown, and how to combine a range slider with a dropdown!
Before you go… If you want to start writing on Medium yourself and earn money passively, you only need a membership for $5 a month. If you sign up with my link, you support me with a part of your membership fee without additional costs.
If you’re interested, here’s a link to more articles I’ve written. There are articles on Python, Generative AI, Expat living, Marathon training, Travel, and more!
More content at PlainEnglish.io.
Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.
