In [1]:
import numpy as np
import pandas as pd

from IPython.display import display

import ezhc as hc


Open console to check js libs were loaded in page

Times series


In [2]:
df = hc.sample.df_timeseries(N=4)

display(df.head())
display(df.tail())


Track1 Track2 Track3 Track4
2015-01-01 1.000000 1.000000 1.000000 1.000000
2015-01-02 0.995581 1.020541 0.995921 0.985524
2015-01-05 0.972516 1.031482 1.000241 0.962263
2015-01-06 0.955501 1.047485 1.024112 0.970548
2015-01-07 0.973585 1.087095 1.009831 0.936838
Track1 Track2 Track3 Track4
2015-05-14 0.733465 1.283439 1.063928 0.817760
2015-05-15 0.722662 1.273534 1.068530 0.829039
2015-05-18 0.739206 1.279543 1.047181 0.811823
2015-05-19 0.719464 1.234844 1.002347 0.800708
2015-05-20 0.710272 1.213259 0.989151 0.788193

In [3]:
g = hc.Highstock()

g.chart.height = 550
g.legend.enabled = True
g.legend.layout = 'horizontal'
g.legend.align = 'center'
g.legend.maxHeight = 100
g.tooltip.enabled = True
g.tooltip.valueDecimals = 2
g.exporting.enabled = True

g.chart.zoomType = 'xy'
g.title.text = 'Time series plotted with HighStock'
g.subtitle.text = 'Transparant access to the underlying js lib'

g.plotOptions.series.compare = 'percent'
g.yAxis.labels.formatter = hc.scripts.FORMATTER_PERCENT
g.tooltip.pointFormat = hc.scripts.TOOLTIP_POINT_FORMAT_PERCENT

# g.plotOptions.series.compare = 'value'
# g.yAxis.labels.formatter = hc.scripts.FORMATTER_OTHER
# g.tooltip.pointFormat = hc.scripts.TOOLTIP_POINT_FORMAT_OTHER

g.tooltip.positioner = hc.scripts.TOOLTIP_POSITIONER

g.xAxis.gridLineWidth = 1.0
g.xAxis.gridLineDashStyle = 'Dot'
g.yAxis.gridLineWidth = 1.0
g.yAxis.gridLineDashStyle = 'Dot'

g.series = hc.build.series(df)

g.plot()


Out[3]:

Column, Bar


In [4]:
df = hc.sample.df_one_idx_several_col()
df


Out[4]:
Jane Joe John
Fruit
Apples 2 3 5
Oranges 2 4 3
Pears 3 4 4
Grapes 2 2 7
Bananas 1 5 2

In [5]:
g = hc.Highcharts()

g.chart.type = 'column'
g.chart.width = 500
g.chart.height = 300
# g.plotOptions.column.animation = False

g.title.text = 'Basic Bar Chart'
g.yAxis.title.text = 'Fruit Consumption'

g.xAxis.categories = list(df.index)
g.series = hc.build.series(df)

g.plot()


Out[5]:

In [6]:
g.plotOptions.column.stacking = 'normal'
g.title.text = 'Stack Bar Chart'
g.yAxis.title.text = 'Total Fruit Consumption'

g.plot()


Out[6]:

In [7]:
g.plotOptions.column.stacking = 'percent'
g.yAxis.title.text = 'Fruit Consumption Distribution'

g.plot()


Out[7]:

In [8]:
g = hc.Highcharts()

g.chart.type = 'bar'
g.chart.width = 500
g.chart.height = 400

g.title.text = 'Basic Bar Chart'
g.xAxis.title.text = 'Fruit Consumption'

g.xAxis.categories = list(df.index)
g.series = hc.build.series(df)

g.plot()


Out[8]:

In [9]:
g.plotOptions.bar.stacking = 'normal'

g.title.text = 'Stacked Bar Chart'
g.xAxis.title.text = 'Total Fruit Consumption'

g.plot()


Out[9]:

In [10]:
g.plotOptions.bar.stacking = 'percent'

g.title.text = 'Stacked Bar Chart'
g.xAxis.title.text = 'Fruit Consumption Distribution'

g.plot()


Out[10]:

Pie


In [11]:
df = hc.sample.df_one_idx_one_col()
df


Out[11]:
MktShare
Brand
Firefox 45.0
IE 26.8
Chrome 12.8
Safari 8.5
Opera 6.2
Others 0.7

In [12]:
g = hc.Highcharts()

g.chart.type = 'pie'
g.chart.width = 400
g.chart.height = 400
gpo = g.plotOptions.pie
gpo.showInLegend = True
gpo.dataLabels.enabled = False

g.title.text = 'Browser Market Share'

g.series = hc.build.series(df)

g.plot()


Out[12]:

In [13]:
g.chart.width = 400
g.chart.height = 300

gpo.showInLegend = False
gpo.dataLabels.enabled = True

gpo.startAngle = -90
gpo.endAngle = 90
gpo.innerSize = '40%'
gpo.center = ['50%', '95%']

g.plot()


Out[13]:

Pie, Column Drilldown


In [14]:
df = hc.sample.df_two_idx_one_col()

df.head()


Out[14]:
Market Share
Brand Version
Internet Explorer 6.0 6.40
7.0 3.55
8.0 26.70
9.0 16.96
Firefox 2.0 0.09

In [15]:
g = hc.Highcharts()

g.chart.type = 'pie'
g.chart.width = 500
g.chart.height = 500
gpo = g.plotOptions.pie
gpo.showInLegend = False
gpo.dataLabels.enabled = True
gpo.center = ['50%', '50%']
gpo.size = '65%'
g.drilldown.drillUpButton.position = {'x': 0, 'y': 0}

g.title.text = 'Browser Market Share'

g.series, g.drilldown.series = hc.build.series_drilldown(df)

g.plot()


Out[15]:

Column Range


In [16]:
df = hc.sample.df_one_idx_two_col()

df.head()


Out[16]:
Min Max
Month
Jan -9.7 9.4
Feb -8.7 6.5
Mar -3.5 9.4
Apr -1.4 19.9
May 0.0 22.6

In [17]:
g = hc.Highcharts()
g.chart.type = 'columnrange'
g.chart.inverted = True
g.chart.width = 700
g.chart.height = 400
gpo = g.plotOptions.columnrange
gpo.dataLabels.enabled = True
gpo.dataLabels.formatter = 'function() { return this.y + "°C"; }'
g.tooltip.valueSuffix = '°C'
g.xAxis.categories, g.series = hc.build.series_range(df)
g.series[0]['name'] = 'Temperature'
g.yAxis.title.text = 'Temperature (°C)'
g.xAxis.title.text = 'Month'
g.title.text = 'Temperature Variations by Month'
g.subtitle.text = 'Vik, Norway'

g.legend.enabled = False

g.plot()


Out[17]:

Scatter


In [18]:
df = hc.sample.df_scatter()

df.head()


Out[18]:
Sex
Height Weight
161.2 51.6 Female
167.5 59.0 Female
159.5 49.2 Female
157.0 63.0 Female
155.8 53.6 Female

In [19]:
g = hc.Highcharts()
g.chart.type = 'scatter'
g.chart.width = 700
g.chart.height = 500
g.chart.zoomType = 'xy'

g.plotOptions.scatter.marker.radius = 5

g.tooltip.headerFormat = '<b>{series.name}</b><br>'
g.tooltip.pointFormat = '{point.x} cm, {point.y} kg'

g.legend.layout = 'vertical'
g.legend.align = 'left'
g.legend.verticalAlign = 'top'
g.legend.x = 100
g.legend.y = 70
g.legend.floating = True
g.legend.borderWidth = 1
                
g.xAxis.title.text = 'Height (cm)'
g.yAxis.title.text = 'Weight (kg)'
g.title.text = 'Height Versus Weight of 507 Individuals by Gender'
g.subtitle.text = 'Source: Heinz 2003'
                
g.series = hc.build.series_scatter(df, color={'Female': 'rgba(223, 83, 83, .5)', 'Male': 'rgba(119, 152, 191, .5)'})

g.plot()


Out[19]:

Bubble


In [20]:
df = hc.sample.df_bubble()

df.head()


Out[20]:
Size
Cat x y
Cat1 97 36 79
94 74 60
68 76 58
64 87 56
68 27 73

In [21]:
g = hc.Highcharts()
g.chart.type = 'bubble'
g.chart.width = 700
g.chart.height = 500
g.chart.zoomType = 'xy'
g.plotOptions.bubble.minSize = 20
g.plotOptions.bubble.maxSize = 60
g.legend.enabled = True
g.title.text = 'Bubbles'

g.series = hc.build.series_bubble(df, color={'A': 'rgba(223, 83, 83, .5)', 'B': 'rgba(119, 152, 191, .5)'})

g.plot()


Out[21]:

Treemap


In [22]:
df = hc.sample.df_several_idx_one_col()

df.head()


Out[22]:
Value
Region Country Cause
Africa Algeria Communicable diseases 97.8
Injuries 53.8
Noncommunicable diseases 710.4
Angola Communicable diseases 873.3
Injuries 137.8

In [23]:
colors = ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9',
          '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1']

df = hc.sample.df_several_idx_one_col()
idx = df.index
col = df.columns
assert(isinstance(idx, pd.core.index.MultiIndex))
assert(len(col)==1)


lev = idx.names
points = []

region_i = 0
for r in idx.levels[0]:
    region_val = 0
    region_p = {
        'id': 'id_' + str(region_i),
        'name': r,
        'color': colors[region_i]
    }
    country_i = 0
    df_reg = df.xs(r).reset_index().set_index([lev[1], lev[2]])
    for co in df_reg.index.levels[0]:
        country_p = {
            'id': region_p['id'] + "_" + str(country_i),
            'name': co,
            'parent': region_p['id'],
        };
        points.append(country_p)
        cause_i = 0
        df_cou = df_reg.xs(co).reset_index().set_index(lev[2])
        for ca in df_cou.index:
            cause_p = {
                'id': country_p['id'] + "_" + str(cause_i),
                'name': ca,
                'parent': country_p['id'],
                'value': round(df_cou.loc[ca]),
            }
            region_val += cause_p['value']
            points.append(cause_p)
            cause_i += 1
        country_i += 1
    region_p['value'] = round(region_val/float(country_i))
    points.append(region_p)
    region_i += 1

points [:5]


Out[23]:
[{'id': 'id_0_0', 'name': 'Algeria', 'parent': 'id_0'},
 {'id': 'id_0_0_0',
  'name': 'Communicable diseases',
  'parent': 'id_0_0',
  'value': 98.0},
 {'id': 'id_0_0_1', 'name': 'Injuries', 'parent': 'id_0_0', 'value': 54.0},
 {'id': 'id_0_0_2',
  'name': 'Noncommunicable diseases',
  'parent': 'id_0_0',
  'value': 710.0},
 {'id': 'id_0_1', 'name': 'Angola', 'parent': 'id_0'}]

In [24]:
g = hc.Highcharts()

g.chart.type = 'treemap'
g.chart.width = 900
g.chart.height = 600

g.title.text = 'Global Mortality Rate 2012, per 100 000 population'
g.subtitle.text = 'Click points to drill down.\nSource: \
                  <a href="http://apps.who.int/gho/data/node.main.12?lang=en">WHO</a>.'

g.series = [{
    'type': "treemap",
    'layoutAlgorithm': 'squarified',
    'allowDrillToNode': True,
    'dataLabels': {
        'enabled': False
    },
    'levelIsConstant': False,
    'levels': [{
        'level': 1,
        'dataLabels': {
            'enabled': True
        },
        'borderWidth': 3
    }],
    'data': points,
}]

g.plot()


Out[24]:

Polar Chart


In [25]:
df = pd.DataFrame(data=np.array([[8, 7, 6, 5, 4, 3, 2, 1],
                                 [1, 2, 3, 4, 5, 6, 7, 8],
                                 [1, 8, 2, 7, 3, 6, 4, 5]]).T,
                  columns=['column', 'line', 'area'])

df


Out[25]:
column line area
0 8 1 1
1 7 2 8
2 6 3 2
3 5 4 7
4 4 5 3
5 3 6 6
6 2 7 4
7 1 8 5

In [26]:
g = hc.Highcharts()

g.chart.polar = True
g.chart.width = 500
g.chart.height = 500

g.title.text = 'Polar Chart'
g.pane.startAngle = 0
g.pane.endAngle = 360
g.pane.background = [{'backgroundColor': '#FFF',
                      'borderWidth': 0
                     }]


g.xAxis.tickInterval = 45
g.xAxis.min = 0
g.xAxis.max = 360
g.xAxis.labels.formatter = 'function() { return this.value + "°"; }'
g.yAxis.min = 0

g.plotOptions.series.pointStart = 0
g.plotOptions.series.pointInterval = 45
g.plotOptions.column.pointPadding = 0
g.plotOptions.column.groupPadding = 0

g.series = [{
    'type': 'column',
    'name': 'Column',
    'data': list(df['column']),
    'pointPlacement': 'between',
    }, {
    'type': 'line',
    'name': 'Line',
    'data': list(df['line']),
    }, {
    'type': 'area',
    'name': 'Area',
    'data': list(df['area']),
    }
]

g.plot()


Out[26]:

Spider Web


In [27]:
df = pd.DataFrame(data=np.array([[43000, 19000, 60000, 35000, 17000, 10000],
                                 [50000, 39000, 42000, 31000, 26000, 14000]]).T,
                  columns=['Allocated Budget', 'Actual Spending'],
                  index = ['Sales', 'Marketing', 'Development', 'Customer Support',
                           'Information Technology', 'Administration'])

df


Out[27]:
Allocated Budget Actual Spending
Sales 43000 50000
Marketing 19000 39000
Development 60000 42000
Customer Support 35000 31000
Information Technology 17000 26000
Administration 10000 14000

In [28]:
g = hc.Highcharts()

g.chart.polar = True
g.chart.width = 650
g.chart.height = 500

g.title.text = 'Budget vs. Spending'
g.title.x = -80

g.pane.size = '80%'
g.pane.background = [{'backgroundColor': '#FFF',
                      'borderWidth': 0
                     }]

g.xAxis.tickmarkPlacement = 'on'
g.xAxis.lineWidth = 0
g.xAxis.categories = list(df.index)

g.yAxis.min = 0
g.yAxis.lineWidth = 0
g.yAxis.gridLineInterpolation = 'polygon'

g.tooltip.pointFormat = '<span style="color:{series.color}">{series.name}: <b>${point.y:,.0f}</b><br/>'
g.tooltip.shared = True


g.legend.align = 'right'
g.legend.verticalAlign = 'top'
g.legend.y = 70
g.legend.layout = 'vertical'

g.series = [{
    'name': 'Allocated Budget',
    'data': list(df['Allocated Budget']),
    'pointPlacement': 'on'
    }, {
    'name': 'Actual Spending',
    'data': list(df['Actual Spending']),
    'pointPlacement': 'on'
    },
]

g.plot()


Out[28]:

Box Plot


In [29]:
df_obs = pd.DataFrame(data=np.array([[760, 801, 848, 895, 965],
                                     [733, 853, 939, 980, 1080],
                                     [714, 762, 817, 870, 918],
                                     [724, 802, 806, 871, 950],
                                     [834, 836, 864, 882, 910]]),
                      index=list('ABCDE'))

display(df_obs)

# x, y positions where 0 is the first category
df_outlier = pd.DataFrame(data=np.array([[0, 644],
                                         [4, 718],
                                         [4, 951],
                                         [4, 969]]))


display(df_outlier)

colors = ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9',
          '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1']


0 1 2 3 4
A 760 801 848 895 965
B 733 853 939 980 1080
C 714 762 817 870 918
D 724 802 806 871 950
E 834 836 864 882 910
0 1
0 0 644
1 4 718
2 4 951
3 4 969

In [30]:
g = hc.Highcharts()

g.chart.type = 'boxplot'
g.chart.width = 850
g.chart.height = 500

g.title.text = 'Box Plot Example'

g.legend.enabled = False

g.xAxis.categories = list(df_obs.index)
g.xAxis.title.text = 'Experiment'

g.yAxis.title.text = 'Observations'
g.yAxis.plotLines= [{
    'value': 932,
    'color': 'red',
    'width': 1,
    'label': {
        'text': 'Theoretical mean: 932',
        'align': 'center',
        'style': { 'color': 'gray' }
    }
}]

g.series = []
g.series.append({
    'name': 'Observations',
    'data': list(df_obs.values),
    'tooltip': { 'headerFormat': '<em>Experiment No {point.key}</em><br/>' },
})
g.series.append({
    'name': 'Outlier',
    'color': colors[0],
    'type': 'scatter',
    'data': list(df_outlier.values),
    'marker': {
        'fillColor': 'white',
        'lineWidth': 1,
        'lineColor': colors[0],
    },
    'tooltip': { 'pointFormat': 'Observation: {point.y}' }
})

g.plot()


Out[30]:

Heatmap


In [31]:
df = hc.sample.df_one_idx_several_col_2()

df


Out[31]:
Alexander Marie Maximilian Sophia Lukas Maria Leon Anna Tim Laura
WeekDay
Monday 10 92 35 72 38 88 13 31 85 47
Tuesday 19 58 15 132 5 32 44 1 97 114
Wednesday 8 78 123 114 8 12 88 82 123 31
Thursday 24 117 64 19 117 6 98 32 64 48
Friday 67 48 52 16 115 120 96 30 84 91

In [32]:
colors = ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9',
          '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1']
idx, col, data = hc.build.series_heatmap(df)

g = hc.Highcharts()

g.chart.type = 'heatmap'
g.chart.width = 650
g.chart.height = 450

g.title.text = 'Sales per employee per weekday'

g.xAxis.categories = idx
g.yAxis.categories = col
g.yAxis.title = ''


g.colorAxis = {
    'min': 0,
    'minColor': '#FFFFFF',
    'maxColor': colors[0],
}

g.legend = {
    'align': 'right',
    'layout': 'vertical',
    'margin': 0,
    'verticalAlign': 'top',
    'y': 25,
    'symbolHeight': 280 
}

g.tooltip = {
    'formatter': """function () {
    return '<b>' + this.series.xAxis.categories[this.point.x] + '</b> sold <br><b>' +
        this.point.value + '</b> items on <br><b>' + this.series.yAxis.categories[this.point.y] + '</b>';
    }"""
}

g.series = []
g.series.append({
    'name': 'Sales per Employee',
    'borderWidth': 1,
    'data': data,
    'dataLabels': {
            'enabled': True,
            'color': '#000000',
    }
})

g.plot()


Out[32]:

Clock


In [33]:
hc.Clock()


Out[33]:

In [ ]:

Direct access to Highcharts/Highstock documentation

  • Navigate the object property tree
  • An info() method gives the official help
  • WARNING: Once a property is set, the info method is not accessible any more

In [34]:
g = hc.Highcharts()

In [35]:
g.yAxis.info()
g.yAxis.labels.format.info()


Documentation for 'yAxis'


  • Description
  • The Y axis or value axis. Normally this is the vertical axis, though if the chart is inverted this is the horizontal axis. In case of multiple axes, the yAxis node is an array of configuration objects.

    See the Axis object for programmatic access to the axis.



    Documentation for 'yAxis.labels.format'


  • Description
  • A format string for the axis label.

  • Demo
  • Add units to Y axis label
    
    
    In [36]:
    g = hc.Highstock()
    
    
    
    In [37]:
    g.plotOptions.info()
    
    
    
    

    Documentation for 'plotOptions'


  • Description
  • The plotOptions is a wrapper object for config objects for each series type. The config objects for each series can also be overridden for each series item as given in the series array.

    Configuration options for the series are given in three levels. Options for all series in a chart are given in the plotOptions.series object. Then options for all series of a specific type are given in the plotOptions of that type, for example plotOptions.line. Next, options for one single series are given in the series array.



    
    
    In [38]:
    g = hc.Highcharts()
    
    
    
    In [39]:
    g.legend.align.info()
    
    
    
    

    Documentation for 'legend.align'


  • Description
  • The horizontal alignment of the legend box within the chart area. Valid values are "left", "center" and "right".

  • Demo
  • Legend at the right of the chart
    
    
    In [ ]: