Quickstart: Patterns and Best Practices


Installation

To install Highcharts Gantt for Python, just execute:

$ pip install highcharts-gantt

Importing Highcharts Gantt for Python Objects

Tip

Best Practice!

This method of importing Highcharts Gantt for Python objects yields the fastest performance for the import statement. However, it is more verbose and requires you to navigate the extensive Highcharts Gantt for Python API.

# Import classes using precise module indications. For example:
from highcharts_gantt.chart import Chart
from highcharts_gantt.global_options.shared_options import SharedGanttOptions
from highcharts_gantt.options import HighchartsGanttOptions
from highcharts_gantt.options.plot_options.gantt import GanttOptions
from highcharts_gantt.options.series.gantt import GanttSeries

Standardizing Your Charts

Tip

Best practice!

We really like to use JS literals written as separate files in our codebase. It makes it super simple to instantiate a SharedGanttOptions instance with one method call.

Let’s say you organize your files like so:

my_repository/
| — docs/
| — my_project/
| —— project_resources/
| ——— image_files/
| ——— data_files/
| ———— data-file-01.csv
| ———— data-file-02.csv
| ———— data-file-03.csv
| ——— highcharts_config/
| ———— shared_options.js
| ———— bar-template-01.js
| ———— bar-template-02.js
| ———— line-template.js
| ———— packed-bubble-template.js
| —— some_package/
| ——— __init__.py
| ——— package_module.py
| ——— another_module.py
| —— __init__.py
| —— __version__.py
| —— some_module.py
| — tests/
| — .gitignore
| — requirements.txt

You’ll notice that the organization has a project_resources folder. This is where you would put the various files that your application wlil reference, like your static images, or the files that contain data you might be using in your application. It also contains a highcharts_config folder, which contains several files with a .js extension. Of particular note is the file in bold, shared_options.js. This file should contain a JavaScript object literal version of the configuration settings you want to apply to all of your visualizations. This file might look something like this:

{
  chart: {
        backgroundColor: {
            linearGradient: {
              x1: 0,
              x2: 0,
              y1: 1,
              y2: 1
            },
            stops: [
                [0, 'rgb(255, 255, 255)'],
                [1, 'rgb(240, 240, 255)']
            ]
        },
        borderWidth: 2,
        plotBackgroundColor: 'rgba(255, 255, 255, .9)',
        plotBorderWidth: 1
  },
  caption: {
      align: 'center',
      floating: true,
      margin: 20,
      verticalAlign: 'top'
  },
  credits: {
      enabled: true,
      href: 'https://www.somewhere.com',
      style: {
          color: '#cccccc',
          fontSize: '8px'
      },
      text: 'Highcharts for Python'
  }
}

Now with this file, you can easily create a SharedGanttOptions instance by executing:

from highcharts_gantt.highcharts import SharedGanttOptions

my_shared_options = SharedGanttOptions.from_js_literal('../../project_resources/highcharts_config/shared_options.js')

And that’s it! Now you have a SharedGanttOptions instance that can be used to apply your configuration standards to all of your charts. You can do that by delivering its JavaScript output to your front-end by calling:

js_code_snippet = my_shared_options.to_js_literal()

which will produce a string as follows:

Highcharts.setOptions({
  caption: {
    align: 'center',
    floating: true,
    margin: 20,
    verticalAlign: 'top'
  },
  chart: {
    backgroundColor: {
      linearGradient: {
        x1: 0.0,
        x2: 0.0,
        y1: 1.0,
        y2: 1.0
      },
      stops: [
        [0, 'rgb(255, 255, 255)'],
        [1, 'rgb(240, 240, 255)']
      ]
    },
    borderWidth: 2,
    plotBackgroundColor: 'rgba(255, 255, 255, .9)',
    plotBorderWidth: 1
  },
  credits: {
    enabled: true,
    href: 'https://www.somewhere.com',
    style: {
      color: '#cccccc',
      fontSize: '8px'
    },
    text: 'Highcharts for Python'
  }
});

And now you can deliver js_code_snippet to your HTML template or wherever it will be rendered.


Populating Series with Data

Note

The .from_asana() method is available on the Chart and GanttSeries classes, allowing you to either assemble a series or an entire chart from an Asana project with only one method call.

from highcharts_gantt.chart import Chart
from highcharts_gantt.options.series.gantt import GanttSeries

# Create a new GanttSeries instance from an Asana project with ID 123456
# - note that this method will automatically read your Asana Personal Access Token from
#   the ASANA_PERSONAL_ACCESS_TOKEN environment variable. You can also supply it
#   directly using the "personal_access_token" keyword argument.
my_series = GanttSeries.from_asana(project_gid = '123456')

# Create a new Chart instance from an Asana project with ID 123456
# - note that this method will automatically read your Asana Personal Access Token from
#   the ASANA_PERSONAL_ACCESS_TOKEN environment variable. You can also supply it
#   directly using the "personal_access_token" keyword argument.
my_chart = Chart.from_asana(project_gid = '123456')

Tip

Where to find my Asana Project GID?

Of course, you can find your Asana Project GID using the Asana API, but that is typically a bit cumbersome. The easiest way to find it is to simply grab it out of your browser’s URL bar:

Asana Project GID
Method Signature

See also

classmethod .from_asana(cls, project_gid, section_gid=None, completed_since=None, use_html_description=True, personal_access_token=None, asana_client=None, api_request_params=None, connection_kwargs=None, connection_callback=None, series_kwargs=None)

Create a GanttSeries instance from an Asana project.

Note

Highcharts Gantt for Python can create an Asana API client for you, authenticating using the Personal Access Token method supported by the Asana API. However, if you wish to use the more-involved OAuth2 handshake process you will need to create your own Asana API client using the asana-python library.

The reason for this is because the OAuth2 handshake has various permutations involving redirects, token refreshes, etc. which are outside the scope of the Highcharts Gantt for Python library, and if you are integrating Highcharts Gantt for Python into a larger application you are likely already facilitating the OAuth2 dance in a fashion appropriate for your use case.

Parameters:
  • project_gid (str) –

    The globally unique ID of the Project whose tasks should be used to assemble the Gantt chart.

    Tip

    You can find your Asana Project GID in your browser URL bar:

    Asana Project GID

  • section_gid (str or None) – The optional unique ID of the section whose tasks should be used to assemble the Gantt chart. Defaults to None, which returns all tasks in the project.

  • completed_since (datetime or None) – An optional filter which only returns tasks that have been completed after this date. Defaults to None, which returns all tasks.

  • use_html_description (bool) – If True, will use the Asana task’s HTML notes in the data point’s .description field. If False, will use the non-HTML notes. Defaults to True.

  • personal_access_token (str or None) – A Personal Access Token created by Asana. Defaults to None, which tries to determine its value by looking in the ASANA_PERSONAL_ACCESS_TOKEN environment variable.

  • api_request_params (dict or None) – Collection of additional request parameters to submit to the Asana API. Defaults to None.

  • connection_kwargs (dict or None) – Set of keyword arugments to supply to the DataConnection constructor, besides the .to property which is derived from the task. Defaults to None

  • connection_callback (Callable or None) –

    A custom Python function or method which accepts two keyword arguments: connection_target (which expects the dependency dict object from the Asana task), and asana_task (which expects the Asana task dict object). The function should return a DataConnection instance. Defaults to None

    Tip

    The connection_callback argument is useful if you want to customize the connection styling based on properties included in the Asana task.

  • series_kwargs (dict or None) – Collection of additional keyword arguments to use when instantiating the GanttSeries (besides the data argument, which will be determined from the Asana tasks). Defaults to None.

Returns:

A GanttSeries populated with data from the indicated Asana project/section.

Return type:

GanttSeries

Raises:
  • HighchartsDependencyError – if the asana Python library is not available in the runtime environment.

  • HighchartsValueError – if connection_callback is not None, but is not callable

  • HighchartsValueError – if asana_client is not None, but is not a valid asana.client.Client> instance

  • AsanaAuthenticationError – if asana_client is not authenticated or if no personal access token is supplied

my_series = LineSeries()

# EXAMPLE 1
# A simple array of numerical values which correspond to the Y value of the data
# point

my_series.data = [0, 5, 3, 5]

# EXAMPLE 2
# An array containing 2-member arrays (corresponding to the X and Y values of the
# data point)

my_series.data = [
    [0, 0],
    [1, 5],
    [2, 3],
    [3, 5]
]

# EXAMPLE 3
# An array of dict with named values

my_series.data = [
  {
      'x': 0,
      'y': 0,
      'name': 'Point1',
      'color': '#00FF00'
  },
  {
      'x': 1,
      'y': 5,
      'name': 'Point2',
      'color': '#CCC'
  },
  {
      'x': 2,
      'y': 3,
      'name': 'Point3',
      'color': '#999'
  },
  {
      'x': 3,
      'y': 5,
      'name': 'Point4',
      'color': '#000'
  }
]

Warning

Technical indicators provided by Highcharts Gantt for Python do not support the .data property because their data gets populated dynamically based on the series indicated in their .linked_to property.

Adding Technical Indicators

Note

All standard series (descending from SeriesBase) have an .add_indicator() method which can be used to easily configure a new indicator tied to the series in question.

# Given a series instance in the variable "my_series"

# Create a Chart instance
my_chart = Chart.from_series(my_series)

# Adds a new Simple Moving Average indicator to the chart, based off of the
# "my_series" series.

my_chart = my_series.add_indicator(my_chart, indicator_name = 'sma')
Method Signature
.add_indicator(chart, indicator_name, indicator_kwargs=None)
Parameters:
  • chart (Chart) – The chart object in which the series is rendered and to which the indicator should be appended.

  • indicator_name (str) – The name of the indicator that should be added to the series and chart. For the list of supported indicators, please review the Indicator List.

  • indicator_kwargs (dict or None) – Keyword arguments to apply when instantiating the new indicator series. Defaults to None.

Returns:

chart with a new indicator series included in its list of configured series.

Return type:

Chart


Assembling Your Chart and Options

Using Keyword Arguments

Note

The keyword pattern outlined below is supported by both the Chart and HighchartsOptions classes

from highcharts_gantt.chart import Chart
from highcharts_gantt.options.series.area import LineSeries

# EXAMPLE 1. Indicating data and series_type.
my_chart = Chart(data = [[0, 1], [1, 2], [2, 3]],
                 series_type = 'line')

# EXAMPLE 2. Supplying the Series instance(s) directly.
my_chart = Chart(series = LineSeries(data = [
                                          [0, 1],
                                          [1, 2],
                                          [2, 3]
                                    ]))

Note

.add_series() is supported by the Chart, HighchartsGanttOptions, and HighchartsStockOptions classes

my_chart = Chart()

my_series = LineSeries()
my_chart.add_series(my_series)
Method Signature
.add_series(self, *series)

Adds series to the Chart.options.series property.

Parameters:

series (SeriesBase or coercable) – One or more series instances (descended from SeriesBase) or an instance (e.g. dict, str, etc.) coercable to one


Rendering Your Visualizations

from highcharts_gantt.chart import Chart
from highcharts_gantt.options.series.gantt import GanttSeries

my_chart = Chart(container = 'target_div',
                 options = {
                     'series': [
                         GanttSeries(data = [
                             ...
                         ])
                     ]
                 },
                 variable_name = 'myChart',
                 is_gantt_chart = True)

as_js_literal = my_chart.to_js_literal()

# This will produce a string equivalent to:
#
# document.addEventListener('DOMContentLoaded', function() {
#   const myChart = Highcharts.ganttChart('target_div', {
#      series: {
#          type: 'gantt',
#          data: [
#            ...
#          ]
#      }
#   });
# });

Downloading a Rendered Highcharts Visualization

from highcharts_gantt.chart import Chart

my_chart = Chart(data = [0, 5, 3, 5],
                 series_type = 'line')

# Download a PNG version of the chart in memory within your Python code.
my_png_image = my_chart.download_chart(format = 'png')

# Download a PNG version of the chart and save it the file "/images/my-chart-file.png"
my_png_image = my_chart.download_chart(
    format = 'png',
    filename = '/images/my-chart-file.png'
)
Method Signature
.download_chart(self, filename=None, format='png', server_instance=None, scale=1, width=None, auth_user=None, auth_password=None, timeout=0.5, global_options=None, **kwargs)

Export a downloaded form of the chart using a Highcharts Export Server.

Parameters:
  • filename (Path-like or None) – The name of the file where the exported chart should (optionally) be persisted. Defaults to None.

  • server_instance (ExportServer or None) – Provide an already-configured ExportServer instance to use to programmatically produce the exported chart. Defaults to None, which causes Highcharts for Python to instantiate a new ExportServer instance with all applicable defaults.

  • format (str) –

    The format in which the exported chart should be returned. Defaults to 'png'.

    Accepts:

    • 'png'

    • 'jpeg'

    • 'pdf'

    • 'svg'

  • scale (numeric) –

    The scale factor by which the exported chart image should be scaled. Defaults to 1.

    Tip

    Use this setting to improve resolution when exporting PNG or JPEG images. For example, setting scale = 2 on a chart whose width is 600px will produce an image file with a width of 1200px.

    Warning

    If width is explicitly set, this setting will be overridden.

  • width (numeric or None) –

    The width that the exported chart should have. Defaults to None.

    Warning

    If explicitly set, this setting will override scale.

  • auth_user (str or None) – The username to use to authenticate against the Export Server, using basic authentication. Defaults to None.

  • auth_password (str or None) – The password to use to authenticate against the Export Server (using basic authentication). Defaults to None.

  • timeout (numeric or None) – The number of seconds to wait before issuing a timeout error. The timeout check is passed if bytes have been received on the socket in less than the timeout value. Defaults to 0.5.

  • global_options (HighchartsStockOptions, HighchartsOptions or None) – The global options which will be passed to the (JavaScript) Highcharts.setOptions() method, and which will be applied to the exported chart. Defaults to None.

Note

All other keyword arguments are as per the ExportServer constructor.

Returns:

The exported chart image, either as a bytes binary object or as a base-64 encoded string (depending on the use_base64 keyword argument).

Return type:

bytes or str


Using Highcharts Stock Features

Stock tools are a custom toolbar that can be displayed on your chart which allows your users to interact with your chart in various ways. Using event bindings tied to the stock tools, you can toggle annotations, toggle technical indicators, or control the chart’s zoom level.

Stock Tools Example

To display the stock tools in your chart, you can use the HighchartsGanttOptions.stock_tools setting, which can be configured using a StockTools instance.

my_stock_tools = StockTools(gui = { 'enabled': True })
my_options = HighchartsGanttOptions(stock_tools = my_stock_tools)
my_chart = Chart.from_options(my_options)