Skip to content

Commit

Permalink
added responsive_flexbox.j2 template and render_template util function
Browse files Browse the repository at this point in the history
  • Loading branch information
bcollins committed Jan 3, 2017
1 parent 137dd7d commit 5978ce6
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 16 deletions.
56 changes: 42 additions & 14 deletions contrib/box_plot/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
from styles import RED, PLOT_FORMATS, DARK_GRAY

from bokeh.models import ColumnDataSource, Range1d
from bokeh.models import CustomJS, RadioButtonGroup
from bokeh.plotting import figure, output_file, show
from bokeh.layouts import row, widgetbox, column
from bokeh.plotting import figure
from bokeh.layouts import column
from bokeh.models.widgets import Div, RadioGroup
from bokeh.embed import components

import pandas as pd
from math import pi

from taxplots.utils import render_template

from styles import RED, PLOT_FORMATS, DARK_GRAY

# create data sources -----------------
source_csv = pd.read_csv('data.csv', parse_dates=[0])
source_csv = source_csv.rename(columns={'Unnamed: 0': 'year'})
Expand Down Expand Up @@ -39,10 +45,22 @@
sources['capital_gains_yes'] = ColumnDataSource(dict(labels=["0.0", "0.25", "0.4", "0.55"],
source_ids=["re10", "re11", "re12", "re13"]))


# create figure ------------------
fig = figure(x_axis_type="datetime", tools=[], responsive=True, **PLOT_FORMATS)
fig = figure(x_axis_type="datetime",
tools=[],
plot_width=400,
plot_height=400,
**PLOT_FORMATS)
fig.set(y_range=Range1d(-9.5, 18.5))
fig.vbar(x='year', top='reform', source=sources['ref'], line_width=20, bottom=0, color=RED, fill_alpha=0.4)
fig.vbar(x='year',
top='reform',
source=sources['ref'],
line_width=20,
bottom=0,
color=RED,
fill_alpha=0.4)

fig.title.align = 'center'
fig.title.text_font_size = '10pt'
fig.yaxis.axis_label = 'Change in individual income and payroll tax liabilities (Billions)'
Expand All @@ -56,17 +74,19 @@
height=1,
color=DARK_GRAY)


# create components --------------
title_div = Div(text='Revenue Impact of a 4% Surtax on Taxpayers with Adjusted Gross Income over $5 Million', width=550, height=30)
title_div = Div(text='Revenue Impact of a 4% Surtax on Taxpayers with Adjusted Gross Income over $5 Million', height=30)

radio_group_text = Div(text="Include Additional Capital Gains Behavior.", width=280, height=18)
radio_group_text = Div(text="Include Additional Capital Gains Behavior.")
radio_group = RadioGroup(labels=["Without", "With"], active=0)
sources['radio_group'] = radio_group

elasticity_text = Div(text="Elasticity of Taxable Income", width=280, height=18)
elasticity_text = Div(text="Elasticity of Taxable Income")
elasticity_option = RadioButtonGroup(labels=sources['capital_gains_no'].data['labels'], active=0)
sources['elasticity_option'] = elasticity_option


# create callbacks ---------------
radio_group.callback = CustomJS(args=sources, code="""
var capitalGainsType = radio_group.active === 0 ? capital_gains_no : capital_gains_yes;
Expand All @@ -86,10 +106,18 @@
ref.trigger('change');
""")

# create layout -----------------
grid = column(column(row(children=[widgetbox(radio_group_text), widgetbox(elasticity_text)]),
row(radio_group, elasticity_option)),
column(title_div, fig))

output_file("index_landscape.html")
show(grid)
# create layout -----------------
controls = column(radio_group_text,
radio_group,
elasticity_text,
elasticity_option)

plots = dict(header=title_div, left=controls, center=fig)
script, divs = components(plots)

template_args = dict()
template_args['bokeh_script'] = script
template_args['plots'] = divs
template_args['page_title'] = 'Box Plot'
render_template('responsive', template_args, 'index.html')
7 changes: 7 additions & 0 deletions taxplots/templates/responsive_flexbox.j2
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@


<body class="plot-body">
<script>
function() {
handle my new componement logic
}
</script>

<header>
{{ plots.header | safe }}
Expand All @@ -53,6 +58,8 @@

<main class="left-content">
{{ plots.left | safe}}
<div class="mycomponent">
</script>
</main>

<nav class="center-content">
Expand Down
29 changes: 27 additions & 2 deletions taxplots/utils.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,41 @@
import os
import yaml

from os import path
from collections import OrderedDict
from jinja2 import Environment, FileSystemLoader

def render_template(template, template_args, output_file):

# register names for known templates
templates = dict(responsive='templates/responsive_flexbox.j2')
here = path.dirname(path.abspath(__file__))

if os.path.exists(template):
template_path = template
elif template in list(templates.keys()):
template_path = templates.get(template)
else:
template_path = path.join(here, 'templates', template)

j2_env = Environment(loader=FileSystemLoader(here), trim_blocks=True)
content = j2_env.get_template(template_path).render(**template_args)
with open(output_file, 'w') as f:
f.write(content)

def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):

class OrderedLoader(Loader):
pass

def construct_mapping(loader, node):
loader.flatten_mapping(node)
return object_pairs_hook(loader.construct_pairs(node))

OrderedLoader.add_constructor(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
construct_mapping)

return yaml.load(stream, OrderedLoader)

class DirectoryContext(object):
Expand All @@ -20,9 +45,9 @@ class DirectoryContext(object):
def __init__(self, path):
self.old_dir = os.getcwd()
self.new_dir = path

def __enter__(self):
os.chdir(self.new_dir)

def __exit__(self, *args):
os.chdir(self.old_dir)

0 comments on commit 5978ce6

Please sign in to comment.