Highcharts Core for Python: Getting Started
We’re so glad you want to use Highcharts Core for Python! This tutorial will help you get started, and give you a jumping off point to dive into all the great features of the Highcharts visualization suite. Before you really get going, we suggest you take a look at all of the great visualization types you can create using Highcharts for Python and Highcharts (JS).
Installation
First things first, to use Highcharts for Python the first step is to install the library (likely to a virtual environment). That’s pretty straightforward:
To install Highcharts Stock for Python, just execute:
$ pip install highcharts-stock
Importing Highcharts Core for Python
Once you’ve installed Highcharts Core for Python, you can import it into your project in two different ways:
Tip
Best Practice!
This method of importing Highcharts Stock for Python objects yields the fastest
performance for the import
statement. However, it is more verbose and requires
you to navigate the extensive Highcharts Stock for Python API.
# Import classes using precise module indications. For example:
from highcharts_stock.chart import Chart
from highcharts_stock.global_options.shared_options import SharedStockOptions
from highcharts_stock.options import HighchartsStockOptions
from highcharts_stock.options.plot_options.bar import BarOptions
from highcharts_stock.options.series.bar import BarSeries
Caution
This method of importing Highcharts Stock for Python classes has relatively slow performance because it imports hundreds of different classes from across the entire library. This performance impact may be acceptable to you in your use-case, but do use at your own risk.
# Import objects from the catch-all ".highcharts" module.
from highcharts_stock import highcharts
# You can now access specific classes without individual import statements.
highcharts.Chart
highcharts.SharedStockOptions
highcharts.HighchartsStockOptions
highcharts.BarOptions
highcharts.BarSeries
Wrangle Your Data
Since you want to use Highcharts Core for Python to visualize some data, first you’re going to have to wrangle the data into a form you can work with. How you do this really depends on the data you are working with and the other tools you are using in your tech stack.
The Highcharts for Python toolkit works with most of the “usual suspects” in the Python ecosystem, including:
For the sake of simplicity, we’ll work with Python iterables to show how you can quickly get started. Let’s say we have a simple 2-dimensional set of x/y values that we want to plot:
my_iterable = [ [0, 123], [1, 456], [2, 789], [3, 987], [4, 654], [5, 321] ]
That’s all I need to wrangle my data! Highcharts for Python can work with
my_iterable
directly and easily, wherever data is referenced.
Tip
Different Highcharts series types support different structures of iterable.
Please review the detailed series documentation for series type-specific details of relevant iterable/array structures.
Alternatively, we can convert my_iterable
into a
pandas.DataFrame
, numpy.ndarray
,
or Python dict
:
# As a Pandas DataFrame df = pandas.DataFrame(my_iterable, columns=['x', 'y']) # As a Numpy ndarray as_ndarray = numpy.asarray(my_iterable) # As a Python dict as_dict = {'x': x[0], 'y': x[1] for x in my_iterable}
Now, we can consider our data “wrangled” and ready for visualization.
Assembling a Chart
With our data wrangled, we can construct a chart with one line of code:
my_chart = Chart(data = my_iterable, series_type = 'line')
This will create a Chart
instance
with one series of type line
(represented as a
LineSeries
instance).
Depending on how we’ve wrangled our data, we can similarly produce a chart
from a pandas.DataFrame
,
numpy.ndarray
, or Python dict
:
# From a Pandas DataFrame my_chart = Chart.from_pandas(df, series_type = 'line') # From a Numpy ndarray my_chart = Chart.from_array(as_ndarray, series_type = 'line') # From a Python dict my_chart = Chart(data = as_dict, series_type = 'line')
All of these lines of code are equivalent, and should produce an identical
my_chart
.
Configuring the Chart
Highcharts (JS) sets the standard for data visualization because it supports a huge number of easy-to-understand configuration options. Highcharts for Python makes it easy to configure any of those options directly within Python.
To do that, we can use the Chart.options
property. Having assembled our chart following the instructions above, my_chart
already contains a HighchartsOptions
instance in the Chart.options
property.
You can access the LineSeries
we created at Chart.options.series
,
and you can set any other options you need on
Chart.options
.
For example, let’s say we want to set the chart’s title to “My First Chart”. To do that,
we can configure the
Chart.options.title
property
using either a Title
instance, or a
dict
:
# as a Title instance from highcharts_stock.options.title import Title my_chart.options.title = Title(text = 'My First Chart') # as a dict my_chart.options.title = {'text': 'My First Chart'}
Either way, the chart’s title will now be set to “My First Chart”.
See also
Templating and Shared Options
Rendering the Chart
Once we’ve assembled and configured our chart, we can render it. How we want to render it depends on our exact needs. We can:
Display the chart in a Jupyter Notebook
Save the chart as a static image
Generate the JavaScript that will render the chart in your users’ web browser.
Displaying in Jupyter Notebook / Jupyter Lab
If you’re using Highcharts Core for Python in a Jupyter Notebook or Jupyter Lab,
you can display the chart right in your notebook. Doing so is super simple - just
call the .display()
method on
my_chart
:
my_chart.display()
That’s it! The chart will now render in the output of the cell.
See also
Using Highcharts Core for Python with Jupyter
Saving the Chart as a Static Image
If you want to save the chart as a static image, you can do so by calling the
.download_chart()
method:
my_chart.download_chart(filename = 'my_chart.png')
If you need it in a different format, you can specify the format using the
format
parameter. Highcharts for Python supports PNG (the default),
JPEG, PDF, and SVG. For example, to save the chart as a PDF, you can do:
my_chart.download_chart(filename = 'my_chart.pdf', format = 'pdf')
And that’s it!
See also
Rendering in the Web Browser
If you want to render your chart in your user’s web browser, then you can
use Highcharts for Python to automatically generate the JavaScript code
you will need. The best way to do this is to call the
.to_js_literal()
method
on my_chart
.
This will produce a string (or write to a file) containing the
JS literal form of your chart and
its configuration. If the code contained in this string gets executed in your
user’s browser (within a set of <script></script>
tags), it will render
your chart.
So the way to get the JS literal is very straightforward:
# EXAMPLE 1. # Storing the JS literal in a string. my_js_literal = my_chart.to_js_literal() # EXAMPLE 2. # Saving the JS literal to a file named # "my-js-literal.js" my_chart.to_js_literal('my-js-literal.js')
Now the way to render this chart will ultimately depend on how your application is architected. We see three - typical - patterns employed:
If your Python code is responsible for preparing the client-side HTML + JavaScript, then you can include
my_js_literal
in your template file. This pattern works for practically every Python web framework, including Django, and Flask.If your Python code exposes RESTful or GraphQL APIs that are consumed by your client-side application, then you can return the JS literal object as a string via your API. This can then be evaluated in your client-side application using JavaScript’s
new Function()
feature.Caution
DO NOT USE JAVASCRIPT’S eval() FUNCTION.
It is deprecated, and for good reason:
It represents a major security risk. When using
new Function()
, we recommend balancing the need for simplicity against the need for security. You can secure your code by applying whitelisting techniques, sandboxing the scope of yournew Function()
context, adding additional layers of M2M signed encryption, or employing sanitization techniques on the content of the JS literal returned by your API.Which specific techniques make sense will depend on your application and your use case.
If the data in your front-end application is generated on a periodic / batch basis, then you can save your JS literal to a static file (saved where consumable by your front-end application) and have your front-end application simply load it as-needed.