avatarJohn Loewen, PhD

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2954

Abstract

"hljs-built_in">df</span>[<span class="hljs-string">'Year'</span>] = pd.to_datetime(<span class="hljs-built_in">df</span>[<span class="hljs-string">'Year'</span>], format=<span class="hljs-string">'%Y'</span>) <span class="hljs-built_in">df</span>[<span class="hljs-string">'65+'</span>] = pd.to_numeric(<span class="hljs-built_in">df</span>[<span class="hljs-string">'65+'</span>], errors=<span class="hljs-string">'coerce'</span>) <span class="hljs-comment"># Filter rows where 'Year' is between 2022 and 2100</span> <span class="hljs-built_in">df</span> = <span class="hljs-built_in">df</span>[(<span class="hljs-built_in">df</span>[<span class="hljs-string">'Year'</span>].dt.year >= 2022) & (<span class="hljs-built_in">df</span>[<span class="hljs-string">'Year'</span>].dt.year <= 2100)]</pre></div><p id="9880">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.</p><h2 id="3849">Creating the Initial Plot and Adding Lines</h2><p id="c558">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.</p><div id="38b7"><pre><span class="hljs-comment"># Subset of countries</span> countries = [<span class="hljs-string">'Burundi'</span>, <span class="hljs-string">'Kenya'</span>, <span class="hljs-string">'Rwanda'</span>, <span class="hljs-string">'Uganda'</span>, <span class="hljs-string">'Japan'</span>, <span class="hljs-string">'Italy'</span>, <span class="hljs-string">'Canada'</span>]

<span class="hljs-comment"># Create the initial plot</span> fig = go.Figure() <span class="hljs-comment"># Add a line for each country</span> <span class="hljs-keyword">for</span> country <span class="hljs-keyword">in</span> countries: country_data = <span class="hljs-built_in">df</span>[<span class="hljs-built_in">df</span>[<span class="hljs-string">'Region, subregion, country or area *'</span>] == country] fig.add_trace(go.Scatter(x=country_data[<span class="hljs-string">'Year'</span>], y=country_data[<span class="hljs-string">'65+'</span>], name=country))</pre></div><h2 id="6bdd">Adding a Range Slider and Displaying the Plot</h2><p id="2f84">Finally, we add a range slider to the x-axis (year) using the <code>rangeslider</code> 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.</p><div id="98d2"><pre><span class="hljs-comment"># Add a range slider</span> fig.update_layout( xaxis=<span class="hljs-built_in">dict</span>( rangeslider=<span class="hljs-built_in">dict</span>(vi

Options

sible=<span class="hljs-literal">True</span>), <span class="hljs-built_in">type</span>=<span class="hljs-string">'date'</span>, <span class="hljs-built_in">range</span>=[<span class="hljs-string">'2022'</span>, <span class="hljs-string">'2100'</span>] ), title=<span class="hljs-string">'Population Index over the Years for Age Group 65+'</span>, xaxis_title=<span class="hljs-string">'Year'</span>, yaxis_title=<span class="hljs-string">'Population Index (%)'</span> ) <span class="hljs-comment"># Show the plot</span> fig.show()</pre></div><p id="00d4">And thats all the code you need. Here is an animated image of how the slider works:</p><figure id="119a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*wDJPj0ecQv-21hMaHFZ-Eg.gif"><figcaption>Python Plotly Animated Range Slider example</figcaption></figure><p id="f3fa">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.</p><p id="4f47">Very useful functionality. Nice work!</p><h1 id="7ebb">In Summary…</h1><p id="8ca6">Adding interactive components like range selectors to your Python data visualizations adds interactivity for your users.</p><p id="6bab">It allows the user to dynamically explore the data within a set range or threshold, providing a more personalized experience.</p><p id="9120">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).</p><p id="1d89">Check out my other articles for how to do a dropdown, and how to combine a range slider with a dropdown!</p><p id="0f21"><b>Before you go… </b><i>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 <a href="https://medium.com/@loewenj700/membership"><b>with my link</b></a>, you support me with a part of your membership fee without additional costs.</i></p><p id="f996"><i>If you’re interested<b>, <a href="https://medium.com/@loewenj700">here’s a link to more articles I’ve written</a>. There are</b> articles on Python, Generative AI, Expat living, Marathon training, Travel, and more!</i></p><p id="c8c1"><i>More content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a>.</i></p><p id="26d0"><i>Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a></i>, <a href="https://www.linkedin.com/company/inplainenglish/"><b><i>LinkedIn</i></b></a><i>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><b>YouTube</b></a>, and <a href="https://discord.gg/GtDtUAvyhW"><b>Discord</b></a><b>.</b></i></p></article></body>

Interactive Python Data Visualization: Adding a Sexy Plotly Range Slider

Implementing a Plotly range slider for added user interactivity

Dall-E Image: impressionist painting of an upward trending line chart

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”.

Data set xlsx file for this example.

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:

Python Plotly Animated Range Slider example

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.

Python
Data Science
Data Visualization
Plotly
Programming
Recommended from ReadMedium