杰瑞科技汇

如何在Python中使用Highcharts?

Of course! Here is a comprehensive guide to using Highcharts with Python, covering the most common methods, from simple examples to best practices.

Highcharts is a powerful, commercial JavaScript charting library. While it's not written in Python, you can generate the necessary JavaScript and HTML code using Python libraries and then render it in a web browser or a Jupyter Notebook.

There are two primary ways to use Highcharts with Python:

  1. Highcharts for Python (Official Library): This is the official, recommended library from Highsoft. It's a Python wrapper that makes it incredibly easy to create charts using Python syntax. It's the best choice for most use cases.
  2. Using highcharts-stock: A popular unofficial library that uses a declarative JSON-like syntax. It's also very effective but is now superseded by the official library.

We will focus on the official Highcharts for Python library as it's the modern, supported, and most feature-rich option.


Method 1: Highcharts for Python (Official & Recommended)

This library allows you to define charts using Python objects and methods, which are then serialized into the Highcharts JavaScript configuration.

Step 1: Installation

First, you need to install the library. It's available on PyPI.

pip install highcharts

Step 2: Your First Chart (Simple Line Chart)

Let's create a basic line chart. The core idea is to create a Chart object, add a Series (your data), and then either display it or save it to an HTML file.

from highcharts import Highchart
# 1. Create a Highchart object
H = Highchart()
# 2. Add data for the series
# Data is a list of [x_value, y_value] pairs
data = [
    [0, 15], [1, 22], [2, 18], [3, 25], 
    [4, 29], [5, 33], [6, 28], [7, 35]
]
# 3. Add the series to the chart
H.add_data_set(data, 'line', 'My First Series')
# 4. Display the chart (in a Jupyter Notebook)
# This will render the chart directly in the cell output.
H

When you run this code in a Jupyter Notebook, you will see an interactive chart appear.

Step 3: Saving to an HTML File

To use the chart in a standalone website or application, you can save it as an HTML file.

from highcharts import Highchart
H = Highchart()
data = [
    [0, 15], [1, 22], [2, 18], [3, 25], 
    [4, 29], [5, 33], [6, 28], [7, 35]
]
H.add_data_set(data, 'line', 'My First Series')
# Save the chart to an HTML file
H.html_export('my_first_chart.html')
print("Chart saved to my_first_chart.html")

This creates a single HTML file that you can open in any web browser.


Advanced Examples with Highcharts for Python

Let's explore more complex charts and features.

Example 1: Bar Chart with Pandas Integration

This is a very common use case. You can easily convert a Pandas DataFrame into a Highcharts series.

import pandas as pd
from highcharts import Highchart
# Sample data
data = {
    'Fruit': ['Apples', 'Bananas', 'Oranges', 'Grapes'],
    'Quantity': [25, 30, 45, 20]
}
df = pd.DataFrame(data)
# Create chart
H = Highchart()
# Convert DataFrame to a list of lists for the series
# We use df.values to get the underlying NumPy array
series_data = df[['Fruit', 'Quantity']].values.tolist()
# Add the series. The 'name' will be used for the legend.
H.add_data_set(series_data, 'bar', 'Fruit Sales')
# You can also customize the chart title and axis labels
H.set_options('title', {'text': 'Fruit Inventory'})
H.set_options('xAxis', {'categories': df['Fruit'].tolist()}) # Use categories for discrete data
H.set_options('yAxis', {'title': {'text': 'Quantity'}})
# Display
H

Example 2: Interactive Scatter Plot with Drilldown

Highcharts is famous for its interactivity. Let's create a scatter plot where you can click on a data point to see more details (drilldown).

from highcharts import Highchart
# Main scatter series data
scatter_data = [
    [10, 12, 'Point A'], # [x, y, name]
    [15, 5, 'Point B'],
    [18, 20, 'Point C'],
    [25, 8, 'Point D']
]
# Drilldown data for each point
drilldown_data = {
    'Point A': {
        'name': 'Details for Point A',
        'data': [[10.1, 11.9], [9.9, 12.1]]
    },
    'Point B': {
        'name': 'Details for Point B',
        'data': [[14.8, 5.2], [15.2, 4.8]]
    }
    # Add more as needed
}
# Create chart
H = Highchart()
# Add the main scatter series
H.add_data_set(scatter_data, 'scatter', 'Main Data', 
                marker={'radius': 8})
# Configure the drilldown
H.set_options('drilldown', {
    'series': list(drilldown_data.values())
})
# Display
H

When you run this, you'll see a scatter plot. Clicking on any point will "drill down" to show a new series with more detailed data for that specific point.


Method 2: Using highcharts-stock (Unofficial, Declarative)

This library is older but still used in some projects. It works by defining the chart configuration as a Python dictionary that closely mirrors the Highcharts JavaScript API JSON structure.

Installation

pip install highcharts-stock

Example: A Simple Line Chart

from highcharts_stock import Highchart
H = Highchart()
# Define the chart options as a dictionary
options = {: {'text': 'Monthly Average Temperature'},
    'xAxis': {
        'categories': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 
                      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
    'yAxis': {
        'title': {'text': 'Temperature (°C)'}
    },
    'series': [{
        'name': 'Tokyo',
        'data': [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    }]
}
# Set the options
H.set_options(options)
# Display in a notebook
H

As you can see, the syntax is more verbose and requires you to know the Highcharts JSON structure. The official library is more "Pythonic."


Best Practices and Considerations

  1. Licensing: Highcharts is a commercial product. The free license is for personal and non-commercial use. For commercial projects, you must purchase a license. The official Python library is part of the Highcharts product ecosystem.

  2. Displaying in Jupyter Notebooks: The official library has excellent integration with Jupyter. Simply calling the chart object at the end of a cell (H) will render it. Make sure you have ipywidgets installed for the best experience (pip install ipywidgets).

  3. Server-Side Rendering (Flask/Django): You can't just return the H object from a web server. You need to get the HTML output and serve it.

    # Example in a Flask route
    from flask import Flask, render_template_string
    from highcharts import Highchart
    app = Flask(__name__)
    @app.route('/')
    def home():
        H = Highchart()
        H.add_data_set([1, 2, 3, 4, 5], 'line', 'Data')
        # Get the HTML representation of the chart
        chart_html = H.content
        # You can embed this into a full HTML template
        full_html = f"""
        <!DOCTYPE html>
        <html>
        <head>
            <title>My Chart</title>
            {H.head} <!-- Includes Highcharts CSS/JS -->
        </head>
        <body>
            <h1>My Chart</h1>
            {chart_html}
        </body>
        </html>
        """
        return render_template_string(full_html)
    if __name__ == '__main__':
        app.run(debug=True)
  4. Performance: For very large datasets (e.g., >10,000 points), consider using highcharts-stock or the official library's streaming capabilities, as they are optimized for performance. The standard Highchart object might become slow with extremely large datasets.

Summary: Which one should I use?

Feature Highcharts for Python (Official) highcharts-stock (Unofficial)
Recommendation Highly Recommended Legacy / Not Recommended for new projects
Syntax Pythonic, object-oriented Declarative, dictionary-based (mirrors JSON)
Maintenance Actively developed by Highsoft Largely unmaintained
Features Full feature parity, latest features May be missing recent features
Licensing Tied to Highcharts commercial license Same underlying Highcharts license
Ease of Use Easier for Python developers Requires knowledge of Highcharts JSON

For any new project, start with the official highcharts library. It's the future-proof, most powerful, and easiest way to integrate Highcharts into your Python workflow.

分享:
扫描分享到社交APP
上一篇
下一篇