Skip to content

Instantly share code, notes, and snippets.

@dylanjm
Last active April 25, 2019 22:18
Show Gist options
  • Save dylanjm/af86239146f9376f36327958324337f6 to your computer and use it in GitHub Desktop.
Save dylanjm/af86239146f9376f36327958324337f6 to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
url = 'https://python-graph-gallery.com/wp-content/uploads/gapminderData.csv'
def add_cols(grp):
grp['popl'] = grp['pop'].apply(lambda x: x/10**5)
grp['gdp_wt'] = np.average(grp['gdpPercap'], weights = grp['pop'])
grp['pop_wt'] = sum(grp['pop'])
return grp
dat = (pd.read_csv(url)
.query('country != "Kuwait"')
.assign(continent = lambda x: x['continent'].astype('category'))
.groupby(['year','continent'])
.apply(add_cols))
size = 5000 * (dat.popl - dat.popl.min()) / (dat.popl.max() - dat.popl.min())
g = sns.FacetGrid(dat, col="year", hue='continent', palette='Set2')
g = g.map(plt.scatter, 'lifeExp', 'gdpPercap', s=size)
g.set(xlabel="", ylabel="")
plt.setp(g.fig.texts, text="")
g.set_titles(col_template="{col_name}")
plt.show()
plt.clf()
# map continental to color
colors = {con:color for con, color in zip(dat.continent.unique(), ['g','b','r','#929705', 'purple'])}
# create palette by country name
pal = {country:colors[con] for country, con in set(zip(dat.country, dat.continent))}
sns.set()
f = sns.FacetGrid(dat, col='continent', hue='country', palette=pal)
f = f.map(plt.plot, 'year', 'gdpPercap', marker='o')
f = f.map(plt.plot, 'year', 'gdp_wt', color='k', marker='o')
f.set(xlabel="", ylabel="")
plt.setp(f.fig.texts, text="")
f.set_titles(col_template="{col_name}")
plt.show()
plt.clf()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment