Share

nbconvert

  |   Source
In [9]:
from IPython.nbformat import current as nbformat
from pygments.formatters import HtmlFormatter
from IPython.nbconvert.exporters import HTMLExporter
from IPython.config import Config
from IPython.nbconvert.filters.highlight import _pygments_highlight
from IPython.display import clear_output, display, HTML
In [10]:
with open('highchart.ipynb') as f:
    double11_notebook = nbformat.reads_json(f.read())
In [11]:
def my_highlight(source, language='ipython'):
    formatter = HtmlFormatter(cssclass='highlight-ipynb')
    return _pygments_highlight(source, formatter, language)
        
c = Config({'CSSHtmlHeaderTransformer':
                    {'enabled':True, 'highlight_class':'highlight-ipynb'}})

exportHtml = HTMLExporter( config=c, filters={'highlight': my_highlight} )
body, resources = exportHtml.from_notebook_node(double11_notebook)
In [12]:
from jinja2 import DictLoader

dl = DictLoader({'full.tpl': 
"""
{%- extends 'basic.tpl' -%} 

{% block footer %}
FOOOOOOOOTEEEEER
{% endblock footer %}
"""})

exportHtml = HTMLExporter(config=None , filters={'highlight': my_highlight}, extra_loaders=[dl])
body, resources = exportHtml.from_notebook_node(double11_notebook)
In [13]:
HTML(body)
Out[13]:
In [4]:
import json
from collections import defaultdict
from datetime import datetime
from IPython.display import HTML

data = json.loads(open('data/commit_activity.json').read())
series = defaultdict(int)
for d in data:
    month = datetime.fromtimestamp(d['week']).month
    series[month] += d['total']
In [5]:
HTML('''
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

<div id="chart" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<script>
    do_chart = function() {

        $('#chart').highcharts({
            chart: {
                type: 'line',
                marginRight: 130,
                marginBottom: 25
            },
            title: {
                text: 'Last Year of commit activity',
                x: -20
            },
            subtitle: {
                text: 'https://github.com/mitsuhiko/flask',
                x: -20
            },
            xAxis: {
                categories: Highcharts.getOptions().lang.shortMonths
            },
            yAxis: {
                title: {
                    text: 'commits'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                valueSuffix: 'number'
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -10,
                y: 100,
                borderWidth: 0
            },
            series: %s
        });

    }
    setTimeout("do_chart()", 50)
</script>
''' % [{'name': 'flask', 'data': series.values()}])
Out[5]:
In [6]:
import json
from collections import defaultdict
from datetime import datetime

import jinja2
from IPython.html.widgets import interact
from IPython.html import widgets
from IPython.display import display, display_pretty, Javascript, HTML
from IPython.utils.traitlets import Any, Bool, Dict, List, Unicode
In [7]:
%%javascript
require.config({
    paths: {
        chartjs: '//code.highcharts.com/highcharts',
        highcharts: '//code.highcharts.com/modules/exporting',
        sandsignika: '//www.highcharts.com/js/themes/sand-signika',
    },
    shim: {
        highcharts: {
            'deps': ['chartjs', 'sandsignika']
        }
    }
});
In [8]:
def display_chart_highcharts(show_javascript, show, div):
    template = """
    require(["highcharts"], function() {
        $('#chart_highcharts').highcharts({
            chart: {
                type: '{{ chart_type }}'
            },
            title: {
                text: '{{ title }}',
                x: -20 //center
            },
            subtitle: {
                text: 'https://github.com/mitsuhiko/flask',
                x: -20
            },
            xAxis: {
                categories: Highcharts.getOptions().lang.shortMonths
            },
            yAxis: {
                title: {
                    text: '{{ yaxis }}'
                }
            },
            plotOptions: {{ plot }},
            series: {{ series }}
        });
    });
    """
    
    with open('data/{}.json'.format(show.replace('by_', ''))) as f:
        data = json.loads(f.read())
    chart_type = 'line'
    plot = '{}'
    if show == 'by_code_frequency':
        pos_series = defaultdict(int)
        nag_series = defaultdict(int)
        for week, pos, nag in data:
            month = datetime.fromtimestamp(week).month
            pos_series[month] += pos
            nag_series[month] += -nag
        series = [{
                'name': 'additions',
                'data': pos_series.values()
            }, {
                'name': 'deletions ',
                'data': nag_series.values()
            }]
        title = 'Get the number of additions and deletions per week'
        yaxis = 'aggregate of the number'
        chart_type = 'column'
        plot = """{
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            }"""
    elif show == 'by_contributors':
        data = sorted(data, key=lambda x: x['total'], reverse=True)[:5]
        series = []
        for i in data:
            name = i['author']['login']
            _series = defaultdict(int)
            for d in i['weeks']:
                month = datetime.fromtimestamp(d['w']).month
                _series[month] += (d['a'] + d['c'] + d['d'])
            series.append({
                'name': name.encode('utf-8'),
                'data': _series.values()
            })
        title = 'Get contributors list with additions, deletions, and commit counts'
        yaxis = 'commit number'
            
    rendered_template = jinja2.Template(template).render(
        title=title, yaxis=yaxis, series=series,
        chart_type=chart_type, plot=plot
    )
    
    if show_javascript:
        display(widgets.PopupWidget(children=(widgets.HTMLWidget(
            value='<div style="width:600px; height: 400px; overflow:scroll;"><pre>{}</pre></div>'.format(rendered_template)),)))
    display(Javascript(rendered_template))

i = interact(
    display_chart_highcharts,
    show_javascript=widgets.CheckboxWidget(value=False),
    show=widgets.DropdownWidget(
        values={'Code frequency':'by_code_frequency', 'Contributors': 'by_contributors'},
        value='by_contributors'
    ),
    div=widgets.HTMLWidget(value='<div id="chart_highcharts"></div>')
)
FOOOOOOOOTEEEEER
Share