Highcharts - Documentation

What is Highcharts?

Highcharts is a powerful, flexible JavaScript charting library used to create interactive and visually appealing charts directly within web pages. It’s renowned for its ease of use, extensive feature set, and support for a wide variety of chart types, making it suitable for a broad range of applications, from simple data visualizations to complex dashboards. Highcharts handles everything from data processing and rendering to user interaction, providing developers with a streamlined way to integrate charts into their projects. It’s built to be responsive, adapting seamlessly to various screen sizes and devices.

Key Features and Benefits

Highcharts boasts a number of key features and benefits that make it a popular choice for web developers:

Getting Started: Installation and Setup

There are several ways to include Highcharts in your project:

  1. Download: Download the Highcharts JavaScript files from the official website and include them in your HTML file using <script> tags. This method is suitable for offline use or situations where you have limited internet access.

  2. CDN: Include Highcharts using a Content Delivery Network (CDN) link. This is a convenient and efficient way to access the library without needing to download and manage the files yourself. A typical CDN link would look like this:

    <script src="https://code.highcharts.com/highcharts.js"></script>

    Remember to check the official Highcharts website for the most up-to-date CDN link. You might also need to include additional modules depending on the chart types you’ll use (e.g., highcharts-more.js for additional chart types).

Basic Chart Creation: A Simple Example

This example demonstrates creating a simple line chart:

<!DOCTYPE html>
<html>
<head>
<title>Highcharts Example</title>
<script src="https://code.highcharts.com/highcharts.js"></script> </head>
<body>
<div id="container"></div>
<script>
Highcharts.chart('container', {
    chart: {
        type: 'line'
    },
    title: {
        text: 'Simple Line Chart'
    },
    series: [{
        data: [1, 2, 3, 4, 5]
    }]
});
</script>
</body>
</html>

This code creates a simple line chart displaying the data points [1, 2, 3, 4, 5]. Replace "https://code.highcharts.com/highcharts.js" with your chosen method of including the Highcharts library. The div with the id “container” serves as a placeholder for the chart. This basic example provides a foundation for building more complex charts. Remember to consult the Highcharts API documentation for detailed information on available options and customization possibilities.

Chart Types

Line Charts

Line charts display data as a series of points connected by straight lines. They are ideal for showing trends over time or illustrating relationships between two variables. Highcharts provides options for customizing line styles, marker shapes, and data labels. Multiple series can be displayed on a single chart for comparison. Features like smoothing and data grouping enhance readability and visual appeal.

Area Charts

Area charts are similar to line charts but fill the area between the line and the x-axis. This emphasizes the magnitude of the data values. Stacked area charts allow for visualizing the contribution of individual series to the total. Percentage area charts normalize the data to show the proportion of each series. Highcharts offers various customization options for filling styles, transparency, and highlighting specific areas.

Column/Bar Charts

Column charts display data as vertical bars, while bar charts use horizontal bars. They are effective for comparing values across different categories. Highcharts supports stacked column/bar charts, allowing for visualizing the composition of values. 3D column/bar charts add a visual dimension for enhanced presentation. Options for data labels, tooltips, and color customization are available.

Pie Charts

Pie charts display data as slices of a circle, representing proportions of a whole. They are best suited for showing the relative sizes of different categories. Highcharts allows for customized slices, labels, and data tooltips, enhancing the clarity and visual impact of the chart. Options for donut charts (pie charts with a hole in the middle) are also included.

Scatter Charts

Scatter charts display data as individual points on a two-dimensional plane, showing the correlation between two variables. Highcharts allows for customization of marker styles, colors, and sizes. Regression lines can be added to highlight trends in the data. This chart type is valuable for identifying patterns and relationships.

Bubble Charts

Bubble charts are an extension of scatter charts, where the size of each point (bubble) represents a third variable. This adds another dimension to the visualization, allowing for simultaneous representation of three variables. Highcharts enables customization of bubble sizes, colors, and labels.

Area Range Charts

Area range charts display the range of values for a given data series, showing both minimum and maximum values. This is effective for presenting uncertainty or variability in data. Highcharts allows for customization of fill styles and colors for improved visual clarity.

Column Range Charts

Similar to area range charts, column range charts display the range of values for each category using vertical bars, showing both minimum and maximum values. This is especially helpful when comparing ranges across different categories. Customization options are similar to column charts, with added options for range visualization.

Box Plot Charts

Box plot charts (also known as box and whisker plots) display the distribution of data using quartiles. They provide insights into the median, range, and potential outliers. Highcharts allows for visualizing multiple box plots on a single chart for comparison.

Error Bar Charts

Error bar charts extend column or bar charts by adding error bars to represent the uncertainty or variability associated with each data point. Highcharts supports various error bar types, including standard deviation, standard error, and confidence intervals.

Waterfall Charts

Waterfall charts show the cumulative effect of positive and negative values over time or categories. They are particularly useful for visualizing financial data or project budgets. Highcharts supports customized labels and styling for improved readability.

Funnel Charts

Funnel charts visually represent the stages in a process, showing how the quantity of items decreases at each step. They are commonly used for marketing or sales funnels. Highcharts offers options for customizing funnel shapes and labels.

Pyramid Charts

Pyramid charts are similar to funnel charts but show both increasing and decreasing quantities. They are suitable for visualizing hierarchical structures or population pyramids. Customization is similar to funnel charts.

Gauge Charts

Gauge charts display a single value on a circular or radial scale, often used to represent metrics like speed, temperature, or performance indicators. Highcharts allows for customizable dials, scales, and pointers.

Heatmaps

Heatmaps use color gradients to represent data values across a two-dimensional grid. They are effective for showing patterns and correlations in large datasets. Highcharts allows for customization of color scales and data labels.

Treemaps

Treemaps display hierarchical data using nested rectangles, where the size of each rectangle represents the value of a data point. They are useful for visualizing proportions within a hierarchy. Highcharts allows for customization of colors, labels, and layout.

Organization Charts

Organization charts visualize hierarchical relationships in an organization or structure. Highcharts provides options for visualizing tree-like structures with customizable nodes and connections.

Maps

Highcharts offers map charting capabilities, allowing for visualization of geographical data. It supports various map projections and data integration methods. Customization includes color scales, tooltips, and interactive features.

Stock Charts

Stock charts are specialized charts for visualizing financial data, typically including OHLC (Open-High-Low-Close) data. Highcharts provides features for candlestick charts, range bars, and various indicators.

Timeline Charts

Timeline charts display events or data points along a timeline, showcasing sequences and durations. Highcharts offers options for customization of timelines, events, and labels.

Solid Gauge

Solid gauge charts are a variation of gauge charts with a solid filled area representing the value instead of a needle pointer. They offer a different visual style for displaying a single metric.

Radial Bar Charts

Radial bar charts display data points as bars radiating from a central point, suitable for comparing values around a central theme. Highcharts allows customization of bar lengths, colors and labels.

Chart Customization

Titles and Labels

Highcharts offers extensive control over chart titles and labels. Titles can be added to the chart overall, as well as to individual axes (X and Y). You can customize text, font styles (size, family, weight, color), alignment, and position. Axis labels can be rotated, formatted (e.g., with units), and spaced for optimal readability. Subtitles can be added below the main title. All these elements contribute significantly to the chart’s overall clarity and understanding. Refer to the API documentation for specific configuration options, such as title, subtitle, xAxis.title, yAxis.title, and xAxis.labels, yAxis.labels.

Axes Customization (X and Y)

Highcharts provides granular control over the X and Y axes. You can customize axis titles (as mentioned above), tick intervals (major and minor), tick positions, label formatting, and the scale type (linear, logarithmic, etc.). Grid lines can be customized with color, width, and style. The axis’s minimum and maximum values can be explicitly set, or allowed to automatically scale to fit the data. Categories can be defined for categorical X-axes. Advanced options include reversed axes, opposite axes, and custom tick mark placement.

Legends

Legends display a key showing the mapping between series and their visual representation (color, marker, etc.) in the chart. Highcharts allows customization of the legend’s position (top, right, bottom, left), layout (horizontal or vertical), and item styling (font, color, marker size). The legend can be enabled or disabled entirely. The legend property in the chart configuration allows control over all these aspects.

Tooltips

Tooltips are interactive pop-up boxes that appear when hovering over data points or chart elements. They display detailed information about the selected data. Highcharts allows customizing the tooltip’s content (using HTML formatting is supported), position, styling, and shared mode (showing information from multiple series simultaneously). The tooltip property offers various options for fine-grained control.

Data Labels

Data labels directly display numerical values or other information on or near data points within the chart. They enhance readability, particularly when dealing with numerous data points or complex charts. Highcharts provides options to customize the label’s position, formatting, and style. You can control whether labels are enabled, their rotation, and the alignment relative to the data point.

Colors and Themes

Highcharts provides options for customizing chart colors using predefined palettes or specifying custom colors for individual series or elements. Pre-built themes offer consistent and aesthetically pleasing combinations of colors and styles. You can also create and apply custom themes for branding consistency across visualizations.

Styling with CSS

While Highcharts handles much of the visual styling internally, you can augment or override the default styling using custom CSS. This allows for fine-grained control over specific aspects of the chart’s appearance without directly modifying the Highcharts JavaScript code. Use CSS selectors targeting Highcharts-generated classes and IDs to achieve the desired visual effects.

Responsive Design

Highcharts automatically adapts to different screen sizes and devices, ensuring consistent rendering across various platforms. However, you can fine-tune this behavior through configuration options to control how the chart behaves at different screen resolutions. This includes responsiveness for legend placement, axis label visibility and resizing.

Accessibility

Highcharts provides features to improve the accessibility of your charts for users with disabilities. This includes ARIA attributes, keyboard navigation, and options for screen reader compatibility. These accessibility features ensure that chart data is accessible to a broader audience, aligning with WCAG guidelines. Proper configuration of these features is critical for inclusive design.

Data Handling

Loading Data from Arrays

The simplest way to provide data to Highcharts is using JavaScript arrays. Each array element represents a data point, and the array itself represents a series. For example:

series: [{
    data: [10, 20, 30, 40, 50]
}]

This code snippet creates a series with five data points. Multiple series can be specified as an array of objects, each containing a data property with its own array of data points. You can also specify names and other properties for each series within these objects.

Loading Data from CSV Files

Highcharts can load data from CSV (Comma Separated Values) files. This requires using the Highcharts data module, which provides functions to parse and load CSV data directly into the chart. The data module needs to be included in your project. Once included, you can use the Highcharts.CSV() function.

For example:

Highcharts.chart('container', {
    chart: { type: 'line' },
    series: [{
        data: Highcharts.csv(csvData), // csvData contains your CSV string
        name: 'My Data'
    }]
});

Where csvData is a string containing your CSV file content. You can load the CSV file content using AJAX or fetch API to get the string before passing it to Highcharts.csv().

Loading Data from JSON Files

Similar to CSV, Highcharts can efficiently handle data from JSON (JavaScript Object Notation) files. JSON is a flexible and widely used format for data exchange. The data can be structured in various ways, allowing for complex series and data structures.

$.getJSON('data.json', function (data) {
    Highcharts.chart('container', {
        series: data
    });
});

This example uses jQuery’s $.getJSON function to fetch JSON data. You can adapt this using the browser’s fetch API or other methods for loading JSON data. The structure of data.json should match the Highcharts series structure.

Loading Data from External APIs

Highcharts can dynamically load data from external APIs (Application Programming Interfaces). This enables creating charts with up-to-date data from various sources. Use JavaScript’s fetch API or libraries like Axios to make requests to the API endpoint and then parse the response (often JSON) before passing it to Highcharts.

For example (using fetch):

fetch('your-api-endpoint')
  .then(response => response.json())
  .then(data => {
    Highcharts.chart('container', { series: data });
  });

Remember to handle potential errors during the API call.

Data Transformations and Preprocessing

Often, raw data needs preprocessing before being used in Highcharts. This can involve calculations, filtering, or reformatting. You can perform these transformations using JavaScript before passing the data to Highcharts. For example, you might calculate moving averages, normalize data, or filter out outliers. Libraries like Lodash or Ramda can simplify these tasks.

Data Point Selection and Filtering

Highcharts itself doesn’t directly handle data filtering, but you can preprocess your data to only include desired points before feeding it to Highcharts. This can be done based on various criteria, like value ranges or date ranges. This allows you to focus on relevant subsets of your data.

Handling Missing Data

Highcharts gracefully handles missing data points. If a data point is missing (e.g., a null or undefined value in your array), Highcharts will usually render a gap in the chart to clearly show the absence of data. You can configure this gap visualization to your liking and even customize the visuals around missing data points.

Large Datasets and Performance Optimization

Rendering large datasets in Highcharts can impact performance. To optimize performance:

Advanced Features

Drilldown and Drillup

Drilldown and drillup functionality allows users to interactively explore hierarchical data. Clicking on a data point in a Highcharts chart can reveal a more detailed view (drilldown), showing granular data related to that point. A drillup feature allows users to navigate back to the higher-level view. This is achieved by defining hierarchical data structures and configuring the chart with the appropriate drilldown settings. This provides powerful interactive data exploration capabilities.

Interactive Elements and Events

Highcharts charts are highly interactive. They respond to various user interactions such as mouse clicks, mouse overs, and zooming. Highcharts provides a rich set of events that can be hooked into to trigger custom actions based on user interactions. These events enable you to create dynamic and responsive applications that react to user activity within the chart. Examples include handling clicks on data points, adding custom context menus, and creating custom interactive elements.

Customizing Tooltips and Events

While Highcharts provides default tooltips, you can extensively customize their content, appearance, and behavior. You can use HTML formatting within tooltips to display rich information. Similarly, you can customize the events triggered by chart interactions, allowing you to create specific actions in response to user interactions such as selecting data points or zooming.

Annotations and Drawings

Highcharts allows you to add annotations and drawings directly onto the chart. This includes adding shapes (rectangles, circles, lines), text labels, or even images at specific locations on the chart. Annotations can highlight significant data points or provide explanatory information. This greatly enhances the communicative power of your visualizations.

Data Grouping and Aggregation

For large datasets, data grouping and aggregation are essential for performance and readability. Highcharts allows you to group and aggregate data points, reducing the number of points rendered while preserving the overall trends. Various aggregation methods (sum, average, etc.) are available, providing flexibility in data summarization.

Exporting Charts (PNG, JPG, PDF, SVG)

Highcharts provides built-in exporting capabilities. You can export the chart to various image formats such as PNG, JPG, and SVG, as well as PDF. The exported charts retain the same styling and formatting as the rendered chart. This feature is crucial for sharing visualizations or including them in reports. The exporting module might require additional configuration or inclusion.

Printing Charts

Highcharts charts can be printed directly from the browser using standard browser print functions. However, you might need to adjust the chart’s layout and styling to optimize the printing output to avoid issues with scaling or cutting off parts of the chart.

Chart Interaction and Zoom

Highcharts supports various chart interactions, including panning and zooming. Users can interactively explore the data by panning across the chart or zooming in to focus on specific areas. This interactive exploration greatly enhances data understanding.

Highcharts Modules and Extensions

Highcharts offers several modules and extensions that expand its capabilities. These modules include additional chart types, features (like maps or stock charts), and functionalities. Adding these modules provides more advanced charting options beyond the core library.

Server-Side Rendering

For applications requiring server-side rendering (SSR), Highcharts can be integrated into server-side frameworks. This allows generating chart images on the server, reducing the client-side load and potentially improving initial load times, especially beneficial for applications with high traffic or limited client-side resources. This often involves generating chart images using server-side libraries and embedding them into the HTML output.

Working with Highcharts Modules

Highcharts’ core functionality can be extended significantly through its various modules. These modules provide specialized chart types, features, and functionalities not included in the base library. To use a module, you need to include its JavaScript file in your project, typically after including the core Highcharts library. Refer to the Highcharts documentation for the correct file names and inclusion methods.

Highcharts Exporting

The Highcharts Exporting module allows you to export your charts in various formats like PNG, JPG, SVG, and PDF. This is crucial for sharing your charts or including them in reports. The module provides server-side and client-side exporting options, though server-side exporting is generally recommended for better performance and reliability, especially with complex charts. Configuration options allow you to customize the exported image’s dimensions, quality, and filename.

Highcharts More

The Highcharts More module adds a collection of additional chart types to the core library. These include charts like the box plot, waterfall, and funnel charts, expanding your visualization options. This module provides more sophisticated and specialized charting capabilities beyond the basic chart types provided in the core library. It enhances the flexibility to choose the best chart for specific data representation.

Highcharts Boost

Highcharts Boost is designed to handle extremely large datasets (millions of data points). It uses WebGL rendering, significantly increasing performance for charts with high data volume that would otherwise be slow or unresponsive. Boost is crucial for interactive exploration of massive datasets without compromising user experience. However, it requires additional setup and configuration.

Highcharts Gantt

Highcharts Gantt is a specialized module for creating Gantt charts, ideal for visualizing project schedules and timelines. It provides features like task dependencies, milestones, and progress tracking. This module is highly useful for project management and scheduling applications, allowing for clear visual representation of task durations, dependencies, and progress.

Highmaps

Highmaps extends Highcharts to handle geographical map data. It allows creating interactive maps that visualize data geographically, using various map projections and data sources. Highmaps integrates with map data providers, allowing you to display data on world maps or custom geographic regions. This module is essential for geographical data visualization and analysis.

Highstock

Highstock is a specialized module for visualizing financial data. It supports candlestick charts, OHLC (Open-High-Low-Close) charts, and various financial indicators, making it ideal for creating stock charts and other financial visualizations. The module includes tools and functionalities specifically tailored for financial data analysis and presentation. It provides advanced features needed for representing and analyzing financial time-series data.

Troubleshooting and Best Practices

Common Errors and Solutions

Several common errors can occur when working with Highcharts. These often relate to incorrect data formats, missing modules, JavaScript errors, or incorrect configuration options. Here are some examples and solutions:

Debugging Techniques

Efficient debugging is crucial for resolving Highcharts issues. Here’s how to approach debugging:

Performance Optimization Strategies

Highcharts performance can be impacted by large datasets, complex chart configurations, and inefficient code. Optimize performance using these strategies:

Best Practices for Chart Design and Usability

Creating effective and usable charts involves understanding data visualization principles and user experience (UX):

Highcharts API Reference

The Highcharts API reference is the definitive source for detailed information on all Highcharts options, methods, and properties. It’s essential to consult the API for specific details on configuring charts, handling events, and customizing various aspects of your charts. The API is well-organized and searchable, making it a valuable resource for developers of all skill levels. The documentation usually provides examples and usage scenarios to aid understanding.

API Reference

The Highcharts API provides comprehensive control over all aspects of chart creation and behavior. This section offers a high-level overview of key API sections. For detailed information and specific options, always consult the official Highcharts API documentation. The examples below are simplified for illustrative purposes.

Core Chart Options

The core chart options define the fundamental structure and appearance of the chart. These options are set within the main chart object.

Highcharts.chart('container', {
    chart: {
        type: 'line', // Chart type (line, bar, pie, etc.)
        renderTo: 'container', // ID of the container element
        height: 400, // Chart height
        width: 600, // Chart width
        backgroundColor: '#FFFFFF' // Background color
    },
    // ... other options ...
});

Options in the chart object control the chart type, dimensions, background, and other overall settings.

Axis Options

Axis options control the appearance and behavior of the X and Y axes. These options are specified within xAxis and yAxis properties (multiple axes are possible).

xAxis: {
    categories: ['Jan', 'Feb', 'Mar'], // Categories for a categorical axis
    title: { text: 'Month' }, // Axis title
    labels: { rotation: -45 } // Rotate labels
},
yAxis: {
    title: { text: 'Sales' },
    min: 0 // Minimum value on the Y-axis
}

Axes options configure titles, labels, tick marks, ranges, and other axis-specific settings.

Series Options

Series options define the properties of each data series displayed on the chart. These are specified within the series array.

series: [{
    name: 'Data Series 1',
    data: [10, 15, 20, 12, 25],
    color: 'blue', // Series color
    type: 'column' // Series type (overrides chart.type if specified)
}, {
    name: 'Data Series 2',
    data: [5, 8, 12, 10, 18],
    color: 'red'
}]

Series options control data, names, colors, types, and other visual aspects of individual data series.

Tooltip Options

Tooltip options control the appearance and behavior of tooltips that appear on mouse hover.

tooltip: {
    headerFormat: '<b>{series.name}</b><br/>',
    pointFormat: '{point.x}: {point.y}'
}

Tooltip options customize the content and formatting of the information displayed in tooltips.

Legend Options

Legend options control the appearance and positioning of the chart legend.

legend: {
    layout: 'vertical',
    align: 'right',
    verticalAlign: 'middle'
}

Legend options define the layout, position, and item styling of the chart legend.

Events

Highcharts provides various events that allow you to respond to user interactions or chart updates. These are attached using the events property.

chart: {
    events: {
        load: function() {
            console.log('Chart loaded');
        }
    }
}

Events allow adding custom functionality triggered at different stages of the chart’s lifecycle.

Methods

Highcharts exposes various methods to dynamically interact with and update the chart. These methods are called on the chart object after it is created.

var chart = Highcharts.chart('container', {/* ... */});

// Add a point to a series:
chart.series[0].addPoint([Date.now(), 30], true, true);

// Update chart options dynamically
chart.update({ chart: { backgroundColor: '#f0f0f0' }});

Methods provide dynamic control over chart updates, data manipulation, and other runtime actions. Always refer to the official Highcharts API documentation for a complete listing of options, events, and methods, along with detailed explanations and examples.