avatarJohn Loewen, PhD

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

7917

Abstract

e code to do the cleaning for you.</p><p id="f2d7">With a larger dataset with more anomalies, this can be a god-send.</p><h1 id="3f91">STEP 2 — Create the Map</h1><p id="1266">Now I want to visualize this information globally on a map. I know Plotly maps can do this for me, so let’s get GPT-4 set up with the right fields and resources to display the results on a map. For now, let’s just choose a valid year and see if GPT-4 can give us the code to display.</p><p id="6c21"><b>Prompt to ChatGPT:</b> I<i> have a csv file named ‘reer_annual_countries.csv’. The first column ‘Country’ contains 3-letter country codes. The following columns contain REER values for each year. Please provide Python code using the Dash and Plotly Express libraries to create a web application that displays a choropleth map of the REER values by country for the year 2020. The color scale should use ‘YlOrRd’. Also, ensure that the title of the map is ‘REER by Country for the Year 2020’</i></p><p id="8162"><b>Response from ChatGPT</b>: <i>Certainly, here is the code:</i></p><div id="fed2"><pre><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd <span class="hljs-keyword">import</span> plotly.express <span class="hljs-keyword">as</span> px <span class="hljs-keyword">import</span> dash <span class="hljs-keyword">from</span> dash <span class="hljs-keyword">import</span> dcc <span class="hljs-keyword">from</span> dash <span class="hljs-keyword">import</span> html

<span class="hljs-comment"># Load the data</span> df = pd.read_csv(<span class="hljs-string">'reer_annual_countries.csv'</span>)

<span class="hljs-comment"># Create a Dash application</span> app = dash.Dash(name)

<span class="hljs-comment"># Create a choropleth map figure for 2020</span> fig = px.choropleth(df, locations=<span class="hljs-string">'Country'</span>, color=<span class="hljs-string">'2020'</span>, locationmode=<span class="hljs-string">'ISO-3'</span>, color_continuous_scale=<span class="hljs-string">'YlOrRd'</span>, title=<span class="hljs-string">'REER by Country for the Year 2020'</span>)

fig.update_layout(margin={<span class="hljs-string">"r"</span>: <span class="hljs-number">10</span>, <span class="hljs-string">"t"</span>: <span class="hljs-number">40</span>, <span class="hljs-string">"l"</span>: <span class="hljs-number">10</span>, <span class="hljs-string">"b"</span>: <span class="hljs-number">20</span>})

<span class="hljs-comment"># Define the layout</span> app.layout = html.Div([ dcc.Graph(<span class="hljs-built_in">id</span>=<span class="hljs-string">'map'</span>, figure=fig) ])

<span class="hljs-comment"># Run the application</span> <span class="hljs-keyword">if</span> name == <span class="hljs-string">'main'</span>: app.run_server(debug=<span class="hljs-literal">True</span>)</pre></div><p id="1ed6">The bulk of the code is the creation of the map, as a choropleth map — and it has a built-in locationmode property that can handle ISO-3 country codes — perfetc.</p><p id="8860">We can copy/paste/run this code using our Python editor — and the Dash app will run on localhost:8050 by default. The browser display will look like:</p><figure id="1e81"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*UplP41Gm-ucdh4AIQX8Dlg.png"><figcaption>REER statistics by country displayed as a Plotly map in Dash (default at localhost:8050)</figcaption></figure><p id="06af">But the problem with this map is that it is static — and it only displays for one year (whichever year we hard-coded).</p><p id="c322">Wouldn’t it be better to create this map as an interactive map? And even better yet, wouldn’t it be great to look at some other pieces of data to get a better picture of exchange rates year-over-year?</p><p id="2ef9">We want to be able to tell a deeper and richer story, and we can do this easily with Plotly Dash.</p><h1 id="6a54">Step 3. Adding Map Interactivity</h1><p id="1057">So let’s add interactivity to allow the user to select each year. We can ask ChatGPT to set up a callback function in Python that uses a dropdown menu to give the user the selection by “Year”.</p><p id="f9c6"><b>Request to ChatGPT</b>: <i>OK, now can you please create a Python plotly dash application that uses a dropdown menu to allow the user to select the year to display the results on a map.</i></p><div id="001b"><pre><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd <span class="hljs-keyword">import</span> plotly.express <span class="hljs-keyword">as</span> px <span class="hljs-keyword">import</span> dash <span class="hljs-keyword">import</span> dash_core_components <span class="hljs-keyword">as</span> dcc <span class="hljs-keyword">import</span> dash_html_components <span class="hljs-keyword">as</span> html <span class="hljs-keyword">from</span> dash.dependencies <span class="hljs-keyword">import</span> Input, Output

<span class="hljs-comment"># Load the data</span> df = pd.read_csv(<span class="hljs-string">'reer_annual_countries.csv'</span>)

<span class="hljs-comment"># Create a list of available years</span> years = df.columns[<span class="hljs-number">1</span>:].tolist()

<span class="hljs-comment"># Create a Dash application</span> app = dash.Dash(name)

<span class="hljs-comment"># Define the layout</span> app.layout = html.Div([ dcc.Dropdown( <span class="hljs-built_in">id</span>=<span class="hljs-string">'year-dropdown'</span>, options=[{<span class="hljs-string">'label'</span>: year, <span class="hljs-string">'value'</span>: year} <span class="hljs-keyword">for</span> year <span class="hljs-keyword">in</span> years], value=years[<span class="hljs-number">0</span>] ), dcc.Graph(<span class="hljs-built_in">id</span>=<span class="hljs-string">'map'</span>) ])

<span class="hljs-comment"># Define the callback</span> <span class="hljs-meta">@app.callback(<span class="hljs-params"> Output(<span class="hljs-params"><span class="hljs-string">'map'</span>, <span class="hljs-string">'figure'</span></span>), [Input(<span class="hljs-params"><span class="hljs-string">'year-dropdown'</span>, <span class="hljs-string">'value'</span></span>)] </span>)</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">update_map</span>(<span class="hljs-params">year</span>): fig = px.choropleth(df, locations=<span class="hljs-string">'Country'</span>, color=year, locationmode=<span class="hljs-string">'ISO-3'</span>, color_continuous_scale=<span class="hljs-string">'YlGn'</span>, title=<span class="hljs-string">f'REER Rate in <span class="hljs-subst">{year}</span>'</span>) <span class="hljs-keyword">return</span> fig

<span class="hljs-comment"># Run the application</span> <span class="hljs-keyword">if</span> name == <span class="hljs-string">'main'</span>: app.run_server(debug=<span class="hljs-literal">True</span>)</pre></div><p id="c9af">This script creates a Dash application with a dropdown menu and a map. In Dash, <b><i>callbacks</i></b> are used to make apps interactive. They are automatically called by Dash whenever an input property changes (like selecting a year).</p><p id="ad11">The <code>@app.callback</code> decorator specifies the dependencies between the components of the app (the input and the output):</p><ul><li><code><b>Output('map', 'figure')</b></code> specifies that the 'figure' property of the 'map' component (which is a <code>dcc.Graph</code> object) will be updated.</li><li><code><b>Input('year-dropdown', 'value')</b></code><b> </b>specifies that the 'value' property of the 'year-dropdown' component (which is a <code>dcc.Dropdown</code> object)has been changed (selected)</li></ul><p id="5097">Every time the ‘value’ of the ‘

Options

year-dropdown’ component changes (i.e., the user selects a different year from the dropdown menu), the callback function <code><b>update_map()</b></code> is called with the new 'value' as the argument.</p><p id="1f60">The <code><b>update_map()</b></code> function generates a new figure for the choropleth map using the selected year's data and returns this figure. Great!</p><figure id="e771"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*_99kZw5gqD4ZBlS9B4ySmQ.png"><figcaption>Dash Dropdown menu in action — callback function is called and map is updated.</figcaption></figure><p id="fffd">The dropdown menu contains all the available years from your data. When the user selects a year from the dropdown menu, the map updates to display the REER rates for that year. Awesome!</p><h1 id="6c2c">Step 4. Adding in Some Charts</h1><p id="90ba">Now lastly, some charts. We can ask GPT-4 for the code to add in two charts below our map:</p><p id="bd89">Prompt to ChatGPT: <i>can you please create a bar chart that displays the top 5 countries each Year that have the highest REER rates. This chart should update when the Year is selected in the dropdown. And can you please create a line chart that displays the global average REER value from 1992–2022. These 2 charts must display on the same row below the map.</i></p><p id="ecb8">A good chunk of the code is exactly the same — we’re still using a callback decorator, but new code must be added to handle updating the “Top 5” chart, the additional charts (a new DIV is created in the layout to display the charts side-by-side), and a function to handle the graphs (updating and displaying):</p><div id="76fb"><pre><span class="hljs-comment"># Define the layout</span> app.layout = html.Div([ dcc.Dropdown( <span class="hljs-built_in">id</span>=<span class="hljs-string">'year-dropdown'</span>, options=[{<span class="hljs-string">'label'</span>: year, <span class="hljs-string">'value'</span>: year} <span class="hljs-keyword">for</span> year <span class="hljs-keyword">in</span> years], value=years[<span class="hljs-number">0</span>] ), dcc.Graph(<span class="hljs-built_in">id</span>=<span class="hljs-string">'map'</span>, style={<span class="hljs-string">'height'</span>: <span class="hljs-string">'60vh'</span>}), html.Div([ dcc.Graph(<span class="hljs-built_in">id</span>=<span class="hljs-string">'top5-countries'</span>, style={<span class="hljs-string">'display'</span>: <span class="hljs-string">'inline-block'</span>, <span class="hljs-string">'width'</span>: <span class="hljs-string">'50%'</span>}), dcc.Graph(<span class="hljs-built_in">id</span>=<span class="hljs-string">'global-reer'</span>, style={<span class="hljs-string">'display'</span>: <span class="hljs-string">'inline-block'</span>, <span class="hljs-string">'width'</span>: <span class="hljs-string">'50%'</span>}) ]) ])

<span class="hljs-comment"># Define the callback for all graphs</span> <span class="hljs-meta">@app.callback(<span class="hljs-params"> [Output(<span class="hljs-params"><span class="hljs-string">'map'</span>, <span class="hljs-string">'figure'</span></span>), Output(<span class="hljs-params"><span class="hljs-string">'top5-countries'</span>, <span class="hljs-string">'figure'</span></span>), Output(<span class="hljs-params"><span class="hljs-string">'global-reer'</span>, <span class="hljs-string">'figure'</span></span>)], [Input(<span class="hljs-params"><span class="hljs-string">'year-dropdown'</span>, <span class="hljs-string">'value'</span></span>)] </span>)</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">update_graphs</span>(<span class="hljs-params">year</span>): <span class="hljs-comment"># Update the map</span> map_fig = px.choropleth(df, locations=<span class="hljs-string">'Country'</span>, color=year, locationmode=<span class="hljs-string">'ISO-3'</span>, color_continuous_scale=<span class="hljs-string">'YlOrRd'</span>, title=<span class="hljs-string">f'REER by Country for the Year <span class="hljs-subst">{year}</span>'</span>) map_fig.update_layout(margin={<span class="hljs-string">"r"</span>: <span class="hljs-number">10</span>, <span class="hljs-string">"t"</span>: <span class="hljs-number">40</span>, <span class="hljs-string">"l"</span>: <span class="hljs-number">10</span>, <span class="hljs-string">"b"</span>: <span class="hljs-number">20</span>})

<span class="hljs-comment"># Update the top 5 countries bar chart</span>
top5 = df[[<span class="hljs-string">'Country'</span>, year]].sort_values(year, ascending=<span class="hljs-literal">False</span>).head(<span class="hljs-number">5</span>)
top5_fig = px.bar(top5, x=<span class="hljs-string">'Country'</span>, y=year, title=<span class="hljs-string">f'Top 5 Countries with Highest REER in <span class="hljs-subst">{year}</span>'</span>,
                  color_discrete_sequence=[<span class="hljs-string">'red'</span>])

<span class="hljs-comment"># Update the global REER line chart</span>
global_fig = px.line(global_reer, x=<span class="hljs-string">'Year'</span>, y=<span class="hljs-string">'REER'</span>, title=<span class="hljs-string">'Global Average REER'</span>,
                     color_discrete_sequence=[<span class="hljs-string">'red'</span>])

<span class="hljs-keyword">return</span> map_fig, top5_fig, global_fig</pre></div><p id="009c">The <b><i>update_graphs()</i></b> function has the biggest changes/additions. There is new code to sort the values for the year selected and then display as a bar chart. And we display the global REER data for each year. Presto!</p><figure id="8b7a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*yn8r3cfs7mnOMyMf2NvSmg.png"><figcaption>Fully interactive dashboard with dropdown menu, map, bar chart and line chart</figcaption></figure><p id="5405">To run this script, copy/paste/save and run it from your Python editor. The Dash application will start a local server and provide a URL where you can access the application from your web browser (the default address/port number is localhost:8050)</p><p id="2cef">Some interesting points about the data:</p><ol><li>The choropleth map adjusts to each year’s maximum value — this can be a little confusing as some years don’t show a lot of color. Find perspective using the Global Average REER.</li><li>The Global average chart provides perspective to the global REER average — the higher the average, the worse of everyone is economically.</li></ol><h1 id="ce7d">To Summarize…</h1><p id="83be">This tutorial illustrates how GPT-4 understands and is able to generate Python code based on user prompts.</p><p id="a90f">When crafted correctly, this drastically reduces the manual coding effort and greatly improves productivity. GPT-4 is not only capable of creating standalone code snippets but can also modify existing code as requirements change.</p><p id="2ce7">Using callback functions to update multiple data visualizations takes a decent amount of skill — this is not simple code.</p><p id="9fe7">GPT-4 makes even these complicated Python data visualization tasks within every Python programmer’s reach.</p><p id="6dd8"><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="a9f7"><i>If you’re interested<b>, <a href="https://medium.com/@loewenj700">here’s a link to more articles I’ve written</a>. </b>There’s articles on Python, Generative AI, Expat living, Marathon training, Travel, and more!</i></p></article></body>

Insanely Powerful Prompts for Python Dashboard Creation

Awesome Plotly results with no hassle using GPT-4 prompts

ChatGPT simplifies and expedites data visualization creation with Python, streamlining the process of cleaning, organizing, and visualizing data.

With GPT-4’s assistance, you can quickly generate code and automate repetitive tasks, saving time and effort.

In this article, we’ll walk you through a 4 step example of how GPT-4 can help you generate Python code:

STEP 1 — clean and transform a dataset

STEP 2 — Visualize the dataset using a Plotly map

STEP 3— Create an interactive Python dash dashboard (to visualize REER rate by Year) to allow selection by Year.

STEP 4 — Create a bar chart and a line chart to add to dashboard

So, buckle up with your GPT-4 bot and your favorite Python editor and get ready to create great stories about your data.

The Dataset: Determining Exchange Rates

The real effective exchange rate (REER) measures the development of the real value of a country’s currency against the basket of the trading partners of the country. bruegul.org recently released this year’s version so this is a great dataset to create a relevant dashboard for.

To start with, the REER dataset can be found and downloaded at: https://www.bruegel.org/publications/datasets/real-effective-exchange-rates-for-178-countries-a-new-database.

The download is in xlsx format and provides real effective exchange rates for 178 countries. The relevant worksheet for this tutorial is the “REER_ANNUAL_170” worksheet — it has exchange rate data for the year range 1992 to 2022.

The first column contains the “Year”, and each subsequent column represents a country — labelled partially with a 2-letter country code- needing some “cleaning”.

So let’s get to it!

STEP 1 — Clean and Transform the Dataset

To clean and transform the dataset, we’ll be using the pandas library in Python, which is a powerful tool for data manipulation and analysis. So, let’s dive into the code and see how we can achieve our data cleaning and transformation tasks!

https://www.bruegel.org/publications/datasets/real-effective-exchange-rates-for-178-countries-a-new-database

Now there’s a lot of things I want done here, so the prompt to sort this out is quite extensive.

One great thing I can do is ask my (extended) query, and then I can ask Python to respond with its interpretation of my request (see below, in bold)

Prompt to ChatGPT: I have a CSV file with REER data called reer_annual.csv. The first column indicates the Year, from 1992–2022. Starting in the second column, each column represents a Country, the heading for each country is using a 2-letter country code as the last 2 letters of each column name. I also have a file called countries.csv with columns “2-letter” and “3-letter” for country codes. I want to convert the 2-letter country codes in the headings to 3-letter codes. If there is not a matching 3-letter country then just drop the row. Can you help me write Python code for this?

Response from ChatGPT: Sure, you can use the pandas library in Python to accomplish this. Here’s a basic outline of what you need to do:

  1. Load the data from reer_annual.csv into a DataFrame.
  2. Load the country codes from countries.csv into another DataFrame.
  3. Create a dictionary to map 2-letter codes to 3-letter codes.
  4. Extract the last 2 letters from each column name in the first DataFrame and convert them to 3-letter codes using the dictionary.
  5. If there is no matching 3-letter code for a 2-letter code, drop the corresponding column.
  6. Assign the new column names to the first DataFrame.

Wow, this is great — I can see if there are any steps that are incorrect, in the wrong order, or missing. Looks good, but I would like to do one more thing to line the data up in a way that makes sense to me. I want to swap the rows and columns in the dataset.

Prompt to ChatGPT: That sounds good. But I also want to swap the rows and columns so that the years are across the top and the years represent each row. I want to keep the ‘Year’ column as is, and do not change the data type or value of each Year. Can you update the Python code for this?

ChatGPT Response: Absolutely, here’s the complete Python script:

import pandas as pd

# Load the data
df = pd.read_csv('reer_annual.csv')

# Load the country codes
country_codes = pd.read_csv('countries.csv')

# Create a dictionary to map 2-letter codes to 3-letter codes
code_dict = dict(zip(country_codes['2-letter'], country_codes['3-letter']))

# Extract the last 2 letters from each column name and convert to 3-letter code
new_columns = [col if col == 'Year' else code_dict.get(col[-2:], None) for col in df.columns]

# Check if there are any None values in new_columns and drop those columns
cols_to_drop = [col for col, new_col in zip(df.columns, new_columns) if new_col is None]
df = df.drop(columns=cols_to_drop)

# Assign the new column names
new_columns = [col for col in new_columns if col is not None]
df.columns = new_columns

# Transpose the dataframe and reset the index
df = df.set_index('Year').T.reset_index()

# Rename the first column as 'Country'
df = df.rename(columns={'index': 'Country'})

# Save the new dataframe to a CSV file
df.to_csv('reer_annual_countries.csv', index=False)

Now I could have spent the time messing around with the CSV file in Excel to clean all the data, but I wanted to prove the point that GPT-4 can handle creating the code to do the cleaning for you.

With a larger dataset with more anomalies, this can be a god-send.

STEP 2 — Create the Map

Now I want to visualize this information globally on a map. I know Plotly maps can do this for me, so let’s get GPT-4 set up with the right fields and resources to display the results on a map. For now, let’s just choose a valid year and see if GPT-4 can give us the code to display.

Prompt to ChatGPT: I have a csv file named ‘reer_annual_countries.csv’. The first column ‘Country’ contains 3-letter country codes. The following columns contain REER values for each year. Please provide Python code using the Dash and Plotly Express libraries to create a web application that displays a choropleth map of the REER values by country for the year 2020. The color scale should use ‘YlOrRd’. Also, ensure that the title of the map is ‘REER by Country for the Year 2020’

Response from ChatGPT: Certainly, here is the code:

import pandas as pd
import plotly.express as px
import dash
from dash import dcc
from dash import html

# Load the data
df = pd.read_csv('reer_annual_countries.csv')

# Create a Dash application
app = dash.Dash(__name__)

# Create a choropleth map figure for 2020
fig = px.choropleth(df, locations='Country', color='2020',
                    locationmode='ISO-3',
                    color_continuous_scale='YlOrRd',
                    title='REER by Country for the Year 2020')

fig.update_layout(margin={"r": 10, "t": 40, "l": 10, "b": 20})

# Define the layout
app.layout = html.Div([
    dcc.Graph(id='map', figure=fig)
])

# Run the application
if __name__ == '__main__':
    app.run_server(debug=True)

The bulk of the code is the creation of the map, as a choropleth map — and it has a built-in locationmode property that can handle ISO-3 country codes — perfetc.

We can copy/paste/run this code using our Python editor — and the Dash app will run on localhost:8050 by default. The browser display will look like:

REER statistics by country displayed as a Plotly map in Dash (default at localhost:8050)

But the problem with this map is that it is static — and it only displays for one year (whichever year we hard-coded).

Wouldn’t it be better to create this map as an interactive map? And even better yet, wouldn’t it be great to look at some other pieces of data to get a better picture of exchange rates year-over-year?

We want to be able to tell a deeper and richer story, and we can do this easily with Plotly Dash.

Step 3. Adding Map Interactivity

So let’s add interactivity to allow the user to select each year. We can ask ChatGPT to set up a callback function in Python that uses a dropdown menu to give the user the selection by “Year”.

Request to ChatGPT: OK, now can you please create a Python plotly dash application that uses a dropdown menu to allow the user to select the year to display the results on a map.

import pandas as pd
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

# Load the data
df = pd.read_csv('reer_annual_countries.csv')

# Create a list of available years
years = df.columns[1:].tolist()

# Create a Dash application
app = dash.Dash(__name__)

# Define the layout
app.layout = html.Div([
    dcc.Dropdown(
        id='year-dropdown',
        options=[{'label': year, 'value': year} for year in years],
        value=years[0]
    ),
    dcc.Graph(id='map')
])

# Define the callback
@app.callback(
    Output('map', 'figure'),
    [Input('year-dropdown', 'value')]
)
def update_map(year):
    fig = px.choropleth(df, locations='Country', color=year,
                        locationmode='ISO-3',
                        color_continuous_scale='YlGn',
                        title=f'REER Rate in {year}')
    return fig

# Run the application
if __name__ == '__main__':
    app.run_server(debug=True)

This script creates a Dash application with a dropdown menu and a map. In Dash, callbacks are used to make apps interactive. They are automatically called by Dash whenever an input property changes (like selecting a year).

The @app.callback decorator specifies the dependencies between the components of the app (the input and the output):

  • Output('map', 'figure') specifies that the 'figure' property of the 'map' component (which is a dcc.Graph object) will be updated.
  • Input('year-dropdown', 'value') specifies that the 'value' property of the 'year-dropdown' component (which is a dcc.Dropdown object)has been changed (selected)

Every time the ‘value’ of the ‘year-dropdown’ component changes (i.e., the user selects a different year from the dropdown menu), the callback function update_map() is called with the new 'value' as the argument.

The update_map() function generates a new figure for the choropleth map using the selected year's data and returns this figure. Great!

Dash Dropdown menu in action — callback function is called and map is updated.

The dropdown menu contains all the available years from your data. When the user selects a year from the dropdown menu, the map updates to display the REER rates for that year. Awesome!

Step 4. Adding in Some Charts

Now lastly, some charts. We can ask GPT-4 for the code to add in two charts below our map:

Prompt to ChatGPT: can you please create a bar chart that displays the top 5 countries each Year that have the highest REER rates. This chart should update when the Year is selected in the dropdown. And can you please create a line chart that displays the global average REER value from 1992–2022. These 2 charts must display on the same row below the map.

A good chunk of the code is exactly the same — we’re still using a callback decorator, but new code must be added to handle updating the “Top 5” chart, the additional charts (a new DIV is created in the layout to display the charts side-by-side), and a function to handle the graphs (updating and displaying):

# Define the layout
app.layout = html.Div([
    dcc.Dropdown(
        id='year-dropdown',
        options=[{'label': year, 'value': year} for year in years],
        value=years[0]
    ),
    dcc.Graph(id='map', style={'height': '60vh'}),
    html.Div([
        dcc.Graph(id='top5-countries', style={'display': 'inline-block', 'width': '50%'}),
        dcc.Graph(id='global-reer', style={'display': 'inline-block', 'width': '50%'})
    ])
])

# Define the callback for all graphs
@app.callback(
    [Output('map', 'figure'),
     Output('top5-countries', 'figure'),
     Output('global-reer', 'figure')],
    [Input('year-dropdown', 'value')]
)
def update_graphs(year):
    # Update the map
    map_fig = px.choropleth(df, locations='Country', color=year,
                            locationmode='ISO-3',
                            color_continuous_scale='YlOrRd',
                            title=f'REER by Country for the Year {year}')
    map_fig.update_layout(margin={"r": 10, "t": 40, "l": 10, "b": 20})

    # Update the top 5 countries bar chart
    top5 = df[['Country', year]].sort_values(year, ascending=False).head(5)
    top5_fig = px.bar(top5, x='Country', y=year, title=f'Top 5 Countries with Highest REER in {year}',
                      color_discrete_sequence=['red'])

    # Update the global REER line chart
    global_fig = px.line(global_reer, x='Year', y='REER', title='Global Average REER',
                         color_discrete_sequence=['red'])

    return map_fig, top5_fig, global_fig

The update_graphs() function has the biggest changes/additions. There is new code to sort the values for the year selected and then display as a bar chart. And we display the global REER data for each year. Presto!

Fully interactive dashboard with dropdown menu, map, bar chart and line chart

To run this script, copy/paste/save and run it from your Python editor. The Dash application will start a local server and provide a URL where you can access the application from your web browser (the default address/port number is localhost:8050)

Some interesting points about the data:

  1. The choropleth map adjusts to each year’s maximum value — this can be a little confusing as some years don’t show a lot of color. Find perspective using the Global Average REER.
  2. The Global average chart provides perspective to the global REER average — the higher the average, the worse of everyone is economically.

To Summarize…

This tutorial illustrates how GPT-4 understands and is able to generate Python code based on user prompts.

When crafted correctly, this drastically reduces the manual coding effort and greatly improves productivity. GPT-4 is not only capable of creating standalone code snippets but can also modify existing code as requirements change.

Using callback functions to update multiple data visualizations takes a decent amount of skill — this is not simple code.

GPT-4 makes even these complicated Python data visualization tasks within every Python programmer’s reach.

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’s articles on Python, Generative AI, Expat living, Marathon training, Travel, and more!

ChatGPT
Python
Data Visualization
AI
Dashboard
Recommended from ReadMedium