'''
US Population Pyramid Over Time
===============================
A population pyramid shows the distribution of age groups within a population.
It uses a slider widget that is bound to the year to visualize the age
distribution over time.
'''
# category: case studies
import altair as alt
from altair.expr import datum, if_
from vega_datasets import data

pop = data.population.url

slider = alt.binding_range(min=1850, max=2000, step=10)
select_year = alt.selection_single(name='year', fields=['year'], bind=slider)

base = alt.Chart(pop).add_selection(
    select_year
).transform_filter(
    select_year
).transform_calculate(
    gender=if_(datum.sex == 1, 'Male', 'Female')
)

title = alt.Axis(title='population')
color_scale = alt.Scale(domain=['Male', 'Female'],
                        range=['#1f77b4', '#e377c2'])

left = base.transform_filter(
    datum.gender == 'Female'
).encode(
    y=alt.X('age:O', axis=None),
    x=alt.X('sum(people):Q', axis=title, sort=alt.SortOrder('descending')),
    color=alt.Color('gender:N', scale=color_scale, legend=None)
).mark_bar().properties(title='Female')

middle = base.encode(
    y=alt.X('age:O', axis=None),
    text=alt.Text('age:Q'),
).mark_text().properties(width=20)

right = base.transform_filter(
    datum.gender == 'Male'
).encode(
    y=alt.X('age:O', axis=None),
    x=alt.X('sum(people):Q', axis=title),
    color=alt.Color('gender:N', scale=color_scale, legend=None)
).mark_bar().properties(title='Male')

left | middle | right
[(15, 'altair.binding_range', 'alt.binding_range', True, 'import altair as alt\n'), (16, 'altair.selection_single', 'alt.selection_single', True, 'import altair as alt\n'), (26, 'altair.Axis', 'alt.Axis', True, 'import altair as alt\n'), (27, 'altair.Scale', 'alt.Scale', True, 'import altair as alt\n'), (23, 'altair.expr.if_', 'if_', False, 'from altair.expr import datum, if_\n'), (18, 'altair.Chart', 'alt.Chart', True, 'import altair as alt\n'), (33, 'altair.X', 'alt.X', True, 'import altair as alt\n'), (35, 'altair.Color', 'alt.Color', True, 'import altair as alt\n'), (39, 'altair.X', 'alt.X', True, 'import altair as alt\n'), (40, 'altair.Text', 'alt.Text', True, 'import altair as alt\n'), (46, 'altair.X', 'alt.X', True, 'import altair as alt\n'), (47, 'altair.X', 'alt.X', True, 'import altair as alt\n'), (48, 'altair.Color', 'alt.Color', True, 'import altair as alt\n'), (34, 'altair.SortOrder', 'alt.SortOrder', True, 'import altair as alt\n')]