How to make a slider to slide across columns to visualize data using plotly and pycountry

220 Views Asked by At

I am trying to create a visual to show country wise GDP across years. My dataframe contains data from 1980 to 2013. A small (made-up) sample of it is here:

Country|1980 YR1980|1981 YR1981|1982 YR 1982|...
     A | 1         |  -        |   2        |...
     B | -         |  1        |   2.5      |...
     c | -         |  0.433    |   4.7      |...

import plotly.express as px
#!pip install pycountry
import pycountry

list_countries = df['Country'].unique().tolist()
d_country_code = {}  # To hold the country names and their ISO
for country in list_countries:
    try:
        country_data = pycountry.countries.search_fuzzy(country)
        # country_data is a list of objects of class pycountry.db.Country
        # The first item  ie at index 0 of list is best fit
        # object of class Country have an alpha_3 attribute
        country_code = country_data[0].alpha_3
        d_country_code.update({country: country_code})
    except:
        print('could not add ISO 3 code for ->', country)
        # If could not find country, make ISO code ' '
        d_country_code.update({country: ' '})
for k, v in d_country_code.items():
    df.loc[(df.Country == k), 'iso_alpha'] = v

fig = px.choropleth(data_frame = df,
                    locations= "iso_alpha",
                    color= "1980",  # value in column 'Confirmed' determines color
                    hover_name= "Country",
                    color_continuous_scale= 'RdYlGn',  #  color scale red, yellow green
                    #animation_frame= "df.iloc()"
                    )

fig.show()

When I am using this code block above, I can visualise data for 1980 but I want to set animation frame so that I can visualize data across years every 5 years. And colors are set by GDP in the specific year column.

How can I achieve my goal.

Do I need to make a list of the columns from 1980 to 2013 and pass them?

Can anyone please help me? Also - if anyone has any other python libraries to suggest that is welcome a well.

0

There are 0 best solutions below