杰瑞科技汇

如何用Python实现Highcharts图表?

Of course! Using Highcharts with Python is a common task for data visualization, especially for creating interactive and publication-quality charts for web applications or reports.

如何用Python实现Highcharts图表?-图1
(图片来源网络,侵删)

The primary way to do this is by generating the chart's configuration in Python and then rendering it on the frontend using the official Highcharts JavaScript library.

Here’s a comprehensive guide covering the main methods, from simple to advanced.

The Core Concept: Python as the Backend, Highcharts as the Frontend

Python itself doesn't render the chart. Instead, your Python code prepares a configuration object (a dictionary in Python) that describes the chart's data, title, axes, series, etc. This configuration is then passed to the Highcharts JavaScript library, which does the actual rendering in the user's browser.

This separation is powerful:

如何用Python实现Highcharts图表?-图2
(图片来源网络,侵删)
  • Python (Backend): Handles data processing, analysis, and generating the chart structure.
  • Highcharts (Frontend): Handles the interactive rendering, animations, and exporting.

Method 1: The Basic Approach (Using highcharts Library)

This is the most straightforward method. The highcharts Python library helps you build the configuration dictionary correctly.

Installation

First, install the Python library:

pip install highcharts

Simple Example: A Line Chart

Let's create a basic line chart. The output will be a JSON string representing the Highcharts configuration.

from highcharts import Highchart
# 1. Initialize the Highchart object
H = Highchart()
# 2. Add the chart title
H.set_options('title', {'text': 'Monthly Average Temperature'})
# 3. Configure the X-axis
H.set_options('xAxis', {
    'categories': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
})
# 4. Configure the Y-axis
H.set_options('yAxis', {: {
        'text': 'Temperature (°C)'
    }
})
# 5. Add the data series
H.add_data_set([
    7.0, 6.9, 9.5, 14.5, 18.2, 21.5,
    25.2, 26.5, 23.3, 18.3, 13.9, 9.6
], 'line', 'Tokyo')
# 6. Print the configuration (this is what you'd send to the frontend)
print(H.to_json())

Running this code will print a large JSON string. This is the configuration that Highcharts needs.

如何用Python实现Highcharts图表?-图3
(图片来源网络,侵删)

Integrating with a Web Framework (Flask Example)

This is where the magic happens. You generate the configuration in a Flask route and pass it to an HTML template.

app.py

from flask import Flask, render_template
from highcharts import Highchart
app = Flask(__name__)
@app.route('/')
def index():
    # --- Chart Generation Logic (same as before) ---
    H = Highchart()
    H.set_options('title', {'text': 'My First Highchart with Flask'})
    H.set_options('xAxis', {'categories': ['A', 'B', 'C']})
    H.set_options('yAxis', {'title': {'text': 'Value'}})
    H.add_data_set([1, 3, 2], 'column', 'Series 1')
    # Convert the chart configuration to a JSON string
    chart_json = H.to_json()
    # Pass the JSON to the HTML template
    return render_template('index.html', chart_json=chart_json)
if __name__ == '__main__':
    app.run(debug=True)

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">Highcharts with Flask</title>
    <!-- 1. Include the Highcharts library from a CDN -->
    <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
    <h1>My Chart</h1>
    <div id="chart-container" style="width: 100%; height: 400px;"></div>
    <script>
        // 2. Parse the JSON string from Python into a JavaScript object
        const chartConfig = {{ chart_json|safe }};
        // 3. Initialize the chart with the configuration
        Highcharts.chart('chart-container', chartConfig);
    </script>
</body>
</html>

Note: The |safe filter is crucial in Jinja2 (Flask's templating engine). It tells Flask not to escape the HTML/JS in the chart_json string.


Method 2: The Pandas Way (Using pandas-highcharts)

If you are already using Pandas for data manipulation, this library is incredibly convenient. It allows you to create a chart directly from a Pandas DataFrame with a single line of code.

Installation

pip install pandas-highcharts

Example: Plotting a DataFrame

This method automatically handles the conversion from DataFrame data to the Highcharts configuration.

import pandas as pd
import pandas_highcharts as hc
# 1. Create a sample DataFrame
data = {
    'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
    'Sales': [100, 150, 200, 180, 240, 300],
    'Expenses': [50, 70, 90, 85, 100, 120]
}
df = pd.DataFrame(data)
# 2. Plot the DataFrame directly
# hc.plot() returns the Highcharts configuration object
chart_config = hc.plot(df, title='Sales vs Expenses', show='inline')
# You can print the config to see it
# print(chart_config.to_json())
# In a web app, you would pass this config to your template
# just like in the Flask example above.

This is much more concise and is the preferred method for data-centric applications.


Method 3: The Manual Approach (No Python Library)

For simple charts, you don't even need a Python library. You can build the configuration dictionary yourself. This is useful for understanding what's under the hood.

import json
# Manually create the configuration dictionary
chart_config = {
    'chart': {
        'type': 'bar' # Type of chart
    },: {
        'text': 'Fruit Consumption'
    },
    'xAxis': {
        'categories': ['Apples', 'Bananas', 'Oranges']
    },
    'yAxis': {
        'title': {
            'text': 'Number of fruits'
        }
    },
    'series': [{
        'name': 'John',
        'data': [3, 5, 1]
    }, {
        'name': 'Jane',
        'data': [2, 7, 4]
    }]
}
# Convert the dictionary to a JSON string
chart_json = json.dumps(chart_config)
# Now you can pass `chart_json` to your frontend, just like before.
print(chart_json)

Advanced Features: Themes and Exporting

The highcharts library also supports advanced features.

Using Themes

Highcharts comes with several built-in themes (like dark-unica, grid-light, etc.).

from highcharts import Highchart
from highcharts.options import HighchartsTheme
# Initialize with a theme
H = Highchart(theme=HighchartsTheme.GRID_LIGHT)
# ... add data and options as before
H.set_options('title', {'text': 'Themed Chart'})
H.add_data_set([5, 7, 3], 'line')

Enabling Exporting

The exporting module allows users to download the chart as an image or PDF.

from highcharts import Highchart
H = Highchart()
# Enable the exporting module
H.set_options('exporting', {
    'enabled': True
})
# ... add data and options
H.set_options('title', {'text': 'Exportable Chart'})
H.add_data_set([10, 15, 13, 17], 'column')

Summary and Recommendation

Method Best For Pros Cons
highcharts Library Full control, complex charts. Great API, good documentation, supports all features. More boilerplate than pandas-highcharts.
pandas-highcharts Data analysis workflows with Pandas. Extremely concise, direct DataFrame plotting. Less flexible for highly customized, non-standard charts.
Manual Dictionary Simple charts or learning the structure. No external dependencies, full transparency. Error-prone, verbose, requires manual JSON conversion.

Recommendation:

  • If you are working with Pandas DataFrames, start with pandas-highcharts. It will save you a lot of time.
  • If you need fine-grained control over every aspect of the chart or are not using Pandas, use the core highcharts library.
  • For a quick and simple chart or to understand the underlying JSON structure, try the manual dictionary approach.
分享:
扫描分享到社交APP
上一篇
下一篇