mf17
mf17

Reputation: 111

How to create a function with Plotly

I am unable to apply a custom function to a data frame without receiving the error message "KeyError: 'state'". See code below.

import plotly.express as px

df = pd.DataFrame({'state':['IL', 'MN', "MN"]})

state_ct = (df
            .groupby(['state'])['state']
            .size()
            .reset_index(name='count'))


def heat_map(df):

    fig = px.choropleth(df,
                        locations=df['state'], 
                        locationmode='USA-states',
                        scope='usa',
                        color='count',
                        color_continuous_scale='reds')

    return(fig.show())

state_ct.apply(heat_map)

However, I can run the plotly code outside of the function with the state_ct data frame and have no issues. What is causing the issue when trying to run this through the custom Python function?

fig = px.choropleth(state_ct,
                    locations=state_ct['state'], 
                    locationmode='USA-states',
                    scope='usa',
                    color='count',
                    color_continuous_scale='reds')

fig.show()

Upvotes: 0

Views: 1289

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31226

import plotly.express as px

df = pd.DataFrame({'state':['IL', 'MN', "MN"]})

state_ct = (df
            .groupby(['state'])['state']
            .size()
            .reset_index(name='count'))


def heat_map(df):

    fig = px.choropleth(df,
                        locations=df['state'], 
                        locationmode='USA-states',
                        scope='usa',
                        color='count',
                        color_continuous_scale='reds')

    return(fig.show())

heat_map(state_ct)

Upvotes: 1

Related Questions