Using Highcharts Maps for Python – Basic Tutorial

Highcharts Maps for Python: Basic Tutorial logo

Highcharts Maps is a powerful JavaScript data visualization library that enables you to design rich, beautiful, and highly interactive data visualizations of geographic information. And using Highcharts Maps for Python, which is part of the broader Highcharts for Python Toolkit, you can easily and rapidly use Highcharts Maps in your Python code.
In addition to providing you with over 70 different base visualizations, Highcharts Maps and Highcharts Maps for Python also give you the capability to construct rich map visualizations including:

  • Zoomable visualizations letting you zoom in and out of your map.
  • The inclusion of dynamic map insets showing more detail or different data to deliver richer insights.
  • Five different map projections to choose from included out of the box, as well as the ability to apply a custom projection algorithm.
  • Support for map definitions in TopoJSON, GeoJSON, or ESRI Shapefile format.

Highcharts Maps for Python will not render data visualizations itself – that’s what Highcharts Maps (in JavaScript) does – but it will allow you to:

  1. Configure your map in Python.
  2. Configure your map data visualizations/interactivity in Python.
  3. Supply data you have in Python to your data visualizations.
  4. Programmatically produce the Highcharts Maps JavaScript code that will actually render your data visualization.
  5. Programmatically download a static version of your visualization (as needed) within Python.


Tip
Think of Highcharts Maps for Python as a translator to bridge your data visualization needs between Python and JavaScript.

Getting Started with Highcharts Maps for Python

To use Highcharts Maps for Python, like with any Python library, you first have to install it. That’s super easy: just open your Python project (in your virtual environment – you are using virtual environments, right?) and execute:

$ pip install highcharts-maps

And that’s it! Highcharts Maps for Python will now be installed in your project and available for use. To use it in your code, you just have to import it the way you would any other library.

What’s Included in Highcharts Maps for Python?

Highcharts Maps for Python is specifically designed to provide rich time series visualization in your Python code. While the base Highcharts for Python library is designed to provide rich interactive visualizations, Highcharts Maps for Python goes further to provide you with:

  • Limitless Mapping – but Batteries Included. While Highcharts Maps for Python lets you easily build custom maps from your own GeoJSON, TopoJSON, or ESRI Shapefile data, you can also leverage one of Highsoft’s existing 500+ maps right out of the box.
  • Rich Data Visualization. Highcharts Maps supports multiple different types of map visualizations, including choropleth (heat map) visualizations, map area visualizations, map line visualizations, map bubble plots, and tilemap representations.
  • Robust Navigation within and across Your Map. Highcharts Maps for Python provides you with the ability to let your users easily navigate to different time periods in your data, using any combination of:
    • Mouse and touch-enabled scrolling and panning.
    • Mouse and touch-enabled zooming.
    • Plus or minus buttons that zoom you in or out, respectively.
  • Custom Projections – but Batteries Included. Highcharts Maps supports five different commonly-used projections out of the box, but it also gives you the ability to write your own custom project projection algorithm easily and quickly.
  • Highcharts for Python. Highcharts Maps for Python includes the complete Highcharts for Python library, with the exact same API. This lets you import one library for all of your data visualization needs, whether working with map data or any other kind of data.

Importing Highcharts Maps for Python

The Highcharts Maps for Python library is quite big. It’s got a rich (read: complicated) API, with lots of different objects and modules. That’s a reflection of the visualization power that Highcharts offers you, but it does make the decision of what to import and how to import it a little more complicated.
Python best practice is to import only what you need, which helps to maximize the performance of your Python code and prevents your application’s namespace from getting cluttered with various things (and further reducing the memory footprint of your Python code, which is always good).

You can either import specific things from their precise locations, or you can also just import the catch-all highcharts module, which flattens the entire API and exposes just about every class/object in one location. We definitely recommend importing things from their precise location like so:

# Import classes using precise module indications. For example:
from highcharts_maps.chart import Chart
from highcharts_maps.global_options.shared_options import SharedMapsOptions
from highcharts_maps.options import HighchartsMapsOptions
from highcharts_maps.options.plot_options.mapbubble import MapBubbleOptions
from highcharts_maps.options.series.mapbubble import MapBubbleSeries

As you can see, the import pattern for Highcharts Maps for Python is very similar to Highcharts for Python. That is because Highcharts Maps for Python is an extension of the Highcharts for Python library, and it maintains the full API. Highcharts Maps features are additive in relation to that API, so you can import from one toolkit library throughout your application.
For example, if you wish to render a Map Bubble chart using Highcharts Maps for Python, but also render a separate Sankey chart (available in Highcharts for Python), you can do both while using the Highcharts Maps for Python library:

from highcharts_maps.chart import Chart
from highcharts_maps.global_options.shared_options import SharedMapsOptions
from highcharts_maps.options import HighchartsMapsOptions
from highcharts_maps.options.plot_options.mapbubble import MapBubbleOptions
from highcharts_maps.options.series.mapbubble import MapBubbleSeries
from highcharts_maps.options.plot_options.sankey import SankeyOptions
from highcharts_maps.options.series.sankey import SankeySeries

A Super Simple Example

While your project is likely more complicated, let’s take a look at the easiest use case: visualizing some data quickly and easily. You likely have your data in a CSV file, or perhaps in a Pandas dataframe, or maybe just stored in a list in your Python code. Highcharts Maps for Python can work with all of those scenarios.

Setup Your Map

When configuring your map visualization, obviously you need to configure the actual map your visualization will be rendering. All maps are defined by their geometries, which is a fancy way of saying they are defined by a very precise definition of the lines and shapes that make up the map.
Typically, your map definition will be stored in either GeoJSON, TopoJSON, or ESRI Shapefile files. Highcharts for Maps natively supports these formats, automatically rendering the maps defined by their content.
The map used in your visualization can be defined in two separate places, either in your chart’s .options.chart.map property, or in a given series’ .map_data property. Both of these properties expect a MapData or AsyncMapData instance, which tells Highcharts Maps where and how to find the geometry to render your map.


Tip
Best practice!: It is recommended to use options.chart.map to configure your visualization’s map. This is because laying out a single visualization that has multiple series represented on multiple maps is a very complicated configuration, and is rarely necessary.

Your map itself is defined using either GeoJSON, TopoJSON, or Shapefile formats. The most important decision you will need to make is whether you wish to load your map data synchronously within Highcharts Maps for Python and then supply the chart definition and the map definition to your (JavaScript) client, or whether you would prefer to load the map definition asynchronously within your (JavaScript) client. Highcharts Maps for Python supports both approaches, and makes doing both very simple.


Tip
Best practice!: Because map data can be verbose and relatively large on the wire, we prefer to rely on the asynchronous method, but there are plenty of valid use cases where the synchronous approach is the best choice.

Using AsyncMapData

You can configure your visualization to load your map data asynchronously by supplying an AsyncMapData instance to either your Chart instance’s .options.chart.map or your Series’ .map_data as described above. The AsyncMapData instance contains a configuration that tells Highcharts for Maps how to have your JavaScript client download (using JavaScript’s fetch()) your map data.

Let’s assume that we have a Chart instance called my_chart. We can configure its map data with one method call:

# Set the chart’s map data, configured to load asynchronously
my_chart.set_map_data('https://code.highcharts.com/mapdata/custom/world.topo.json')

That’s all you have to do! When you now serialize your my_chart variable to JavaScript using the .to_js_literal() method, you will have an asynchronous fetch() call which downloads the world.topo.json data from the URL you provided.

If your asynchronous map data is a bit more complicated, you can create an AsyncMapData instance and simply pass the .set_map_data() method that instance. This is typically used if you want to only use a subset of your topology, or if you need to customize the authentication credentials used when downloading your map geometry.

from highcharts_maps.options.series.data.map_data import AsyncMapData
# An equivalent way of doing this to create an AsyncMapData instance:
my_map_data = AsyncMapData(
    url = 'https://code.highcharts.com/mapdata/custom/world.topo.json'
)
my_chart.set_map_data(my_map_data)

For more details on how to use AsyncMapData, please review the tutorial Highcharts Maps for Python: Working with Asynchronous Map Data.

Using MapData

If you do not want to load your map data asynchronously in your JavaScript client, you can supply your map geometries directly within Python as well, and that map data will then be serialized to JavaScript along with your chart definition when you call .to_js_literal() on your Chart instance.
Synchronous map data is represented as a MapData instance. This object can most easily be created by calling one of its deserializer methods:

Each of these class methods will return a MapData instance whose .topology property will now be populated with your map geometry:

# Load Map Data from a TopoJSON file
my_map_data = MapData.from_topojson('my-map-data.topo.json')
# Load Map Data from a TopoJSON string "my_topojson_string"
my_map_data = MapData.from_topojson(my_topojson_string)
# Load Map Data from a GeoPandas GeoDataFrame “gdf”
my_map_data = MapData.from_geodataframe(gdf)
# Apply the MapData to your chart.
my_chart.set_map_data(my_map_data)

And that’s it! The logic (and even the syntax) is basically the same, regardless of whether you are loading your map geometries from TopoJSON, GeoJSON, an ESRI Shapefile, or a GeoPandas GeoDataFrame instance. Just call the appropriate method. Review the detailed MapData API documentation for more details.

Creating Your Data Series

Using Highcharts Maps for Python, you can configure your chart’s data visualizations exactly the same as you would using any library in the Highcharts for Python toolkit. In general, your data can either reside in a CSV file, a Pandas Dataframe, a PySpark Dataframe, a GeoPandas GeoDataFrame, or even a Python list instance.

Since we’re focusing in this tutorial on Highcharts Maps for Python, let’s assume we have a bunch of our map data in a GeoPandas GeoDataFrame instance called gdf. We can create our MapSeries or chart by calling .from_geodataframe() as shown below:

# Given a geoPandas DataFrame instance named "gdf"
from highcharts_maps.chart
import Chart
from highcharts_maps.options.series.map
import MapSeries
# Creating a Series from the GeoDataFrame
my_series = MapSeries.from_geopandas(gdf,
  property_map = {
    'id': 'state',
    'name': 'state',
    'value': 'value'
  })
# Creating a Chart with a MapSeries from the GeoDataFrame.
my_chart = Chart.from_geopandas(gdf,
  property_map = {
    'id': 'state',
    'name': 'state',
    'value': 'value'
  },
  series_type = 'map')

So what’s happening in the code above? In the first example, we’re creating a MapSeries instance by calling the .from_geopandas() class method on the MapSeries class. We’re telling it to load the series data from the GeoPandas GeoDataFrame instance called gdf, and we’re then providing it a property_map argument.

This property_map argument is “where the magic happens”, since it maps columns of data in your GeoDataFrame to their corresponding properties in your MapSeries .data property (which takes a GeometricData instance).

In this case, we’re telling Highcharts Maps for Python to populate each data point’s .id and .name properties (which give the data point a unique ID and specify the data point’s label, respectively) from the gdf column labeled “state”, and to populate the .value property from the column labeled “value”.

Note
The .from_geopandas() method is available on all series classes which support rendering as a map visualization. This includes:

  • MapSeries
  • MapBubbleSeries
  • MapLineSeries
  • MapPointSeries
  • HeatmapSeries
  • TilemapSeries

Allowing you to either assemble a series or an entire chart from a GeoPandas GeoDataFrame with only one method call.

Other Approaches

The example above focuses on using a GeoPandas GeoDataFrame, but Highcharts Maps for Python has you covered regardless of how you are managing your data in your Python application. You have similar convenience functions for loading data:

You can call these convenience methods on the Chart class as shown above, or you can also call the exact same convenience methods on a series type, and then add the series to a chart instance using the my_chart.add_series() method.

Tip
Our other tutorials show you in detail how to use these different convenience methods to rapidly build great visualizations – we recommend you check out here: Highcharts for Python Tutorials.

Visualizing Your Chart

Now that we’ve built a Chart instance and populated it with data, our next step is to visualize it. How you actually do this depends to some extent on how you are building your Python application.
Maybe you are using a web framework like Flask, Django, or FastAPI and relying on their templating engines for creating your views. Or maybe you are providing a Python backend API which delivers data to an entirely separate app via RESTful API calls. In any case, to visualize your new chart you need to somehow get its configuration to your web-based front-end. And that is super simple as well.
Using the example above, you can generate the full set of HTML and JavaScript content to render your chart with one method call:

as_js_literal = my_chart.to_js_literal()
# This will produce a string similar to:
#
# document.addEventListener('DOMContentLoaded', function() {
#   const myChart = Highcharts.chart('target_div', {
#      series: {
#          type: 'map',
#          data: [
#              ['ny', 7],
#              ['ma', 1],
#              ['nj', 3]
#      }
#   });
# });

So what is this method call doing? It is taking the entire set of instructions included in your my_chart variable, creating a JavaScript literal string that represents them, and putting that string in the as_js_literal Python variable. This string can then be piped into your web front end using whatever templating engine you are using, or delivered to your front-end in an API response, and it will then render your chart as you configured it.
In the example above, if you place the as_js_literal string in what gets rendered in your user’s browser, your chart will be automatically rendered by Highcharts Maps, placing the chart inside the div element in your content whose id is “target_div”.
And that’s it! You should now see a beautiful map chart in your web content.

Downloading Your Chart

Often when you’ve created a visualization, you may want to download a static version of it as an image that can be embedded in other documents. With Highcharts Maps for Python, that is a fairly trivial exercise. Given the example above, you can produce a PNG image very simply with one method call:

# 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'
)

The two examples shown above both download a PNG of your chart:
The first example keeps that PNG image in your Python code only, storing its binary data in the my_png_image variable. The second example not only stores its binary data in the my_png_image variable, but it also saves the PNG image to the file “/images/my-chart-file.png”.

The format argument is really the one doing the heavy lifting above. In the example above tells the method to generate a PNG image, but you can also create “jpeg”, “pdf”, and “svg”.

And that’s it! You should know that the .download_chart() method defaults to using the Highcharts Export Server provided by Highsoft (creators of Highcharts JS), however you can configure the method to use your own custom Highcharts Export Server if you choose. For more details on how to do this, please review our tutorial on Exporting Static Charts using Highcharts for Python.

More Resources

The above tutorial is just a really simple example of how you can create rich visualizations with just a handful of method calls using Highcharts for Python. But the library offers so much more! We recommend you take a look at the following additional resources which you may find useful: