Gapminders#

https://panel.holoviz.org/_static/logo_stacked.png

The Panel library from HoloViz lets you make widget-controlled apps and dashboards from a wide variety of plotting libraries and data types.

Here we set up four different plotting libraries controlled by a couple of widgets, for Hans Rosling’s gapminder example.

import warnings

import numpy as np 
import pandas as pd
import panel as pn

import altair as alt
import plotly.graph_objs as go
import plotly.io as pio
import matplotlib.pyplot as plt
import hvplot.pandas  # noqa

warnings.simplefilter('ignore')
pn.extension('vega', 'plotly', defer_load=True, sizing_mode="stretch_width")

We need to define some configuration

XLABEL = 'GDP per capita (2000 dollars)'
YLABEL = 'Life expectancy (years)'
YLIM = (20, 90)
HEIGHT=500 # pixels
WIDTH=500 # pixels
ACCENT="#00A170"

PERIOD = 1000 # miliseconds

Extract the dataset#

First, we’ll get the data into a Pandas dataframe. We use the built in cache to speed up the app.

@pn.cache
def get_dataset():
    url = 'https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv'
    return pd.read_csv(url)
dataset = get_dataset()
dataset.sample(10)
country year pop continent lifeExp gdpPercap
1181 Panama 1977 1839782.0 Americas 68.681 5351.912144
1400 Somalia 1992 6099799.0 Africa 39.658 926.960296
705 India 1997 959000000.0 Asia 61.765 1458.817442
377 Croatia 1977 4318673.0 Europe 70.640 11305.385170
577 Ghana 1957 6391288.0 Africa 44.779 1043.561537
1147 Norway 1987 4186147.0 Europe 75.890 31540.974800
1290 Rwanda 1982 5507565.0 Africa 46.218 881.570647
320 Comoros 1992 454429.0 Africa 57.939 1246.907370
1567 Tunisia 1987 7724976.0 Africa 66.894 3810.419296
925 Malawi 1957 3221238.0 Africa 37.207 416.369806
YEARS = [int(year) for year in dataset.year.unique()]
YEARS
[1952, 1957, 1962, 1967, 1972, 1977, 1982, 1987, 1992, 1997, 2002, 2007]

Transform the dataset to plots#

Now let’s define helper functions and functions to plot this dataset with Matplotlib, Plotly, Altair, and hvPlot (using HoloViews and Bokeh).

@pn.cache
def get_data(year):
    df = dataset[(dataset.year==year) & (dataset.gdpPercap < 10000)].copy()
    df['size'] = np.sqrt(df['pop']*2.666051223553066e-05)
    df['size_hvplot'] = df['size']*6
    return df

def get_title(library, year):
    return f"{library}: Life expectancy vs. GDP, {year}"

def get_xlim(data):
    return (data['gdpPercap'].min()-100,data['gdpPercap'].max()+1000)

Let’s define the Matplotlib plotting function.

plt.rcParams.update({
    "savefig.facecolor": (0.0, 0.0, 0.0, 0.0), 
})


@pn.cache
def mpl_view(year=1952, show_legend=True):
    data = get_data(year)
    title = get_title("Matplotlib", year)
    xlim = get_xlim(data)

    plot = plt.figure(figsize=(10, 6), facecolor=(0, 0, 0, 0))
    ax = plot.add_subplot(111)
    ax.set_xscale("log")
    ax.set_title(title)
    ax.set_xlabel(XLABEL)
    ax.set_ylabel(YLABEL)
    ax.set_ylim(YLIM)
    ax.set_xlim(xlim)

    for continent, df in data.groupby('continent'):
        ax.scatter(df.gdpPercap, y=df.lifeExp, s=df['size']*5,
                   edgecolor='black', label=continent)

    if show_legend:
        ax.legend(loc=4)

    plt.close(plot)
    return plot

mpl_view(1952, True)
../../_images/43bc4a0b4190ddabd9c1e4db620a04c946528467fcfa8f9502aea2e93d09d31b.png

Let’s define the Plotly plotting function.

pio.templates.default = None

@pn.cache
def plotly_view(year=1952, show_legend=True):
    data = get_data(year)
    title = get_title("Plotly", year)

    traces = []
    for continent, df in data.groupby('continent'):
        marker=dict(symbol='circle', sizemode='area', sizeref=0.1, size=df['size'], line=dict(width=2))
        traces.append(go.Scatter(x=df.gdpPercap, y=df.lifeExp, mode='markers', marker=marker, name=continent, text=df.country))

    axis_opts = dict(gridcolor='rgb(255, 255, 255)', zerolinewidth=1, ticklen=5, gridwidth=2)
    layout = go.Layout(
        title=title, showlegend=show_legend,
        xaxis=dict(title=XLABEL, type='log', **axis_opts),
        yaxis=dict(title=YLABEL, **axis_opts),
        autosize=True, paper_bgcolor='rgba(0,0,0,0)',
    )
    
    return go.Figure(data=traces, layout=layout)

plotly_view()