杰瑞科技汇

Python如何实现Highcharts动态图表?

Of course! Using Python with Highcharts is a fantastic way to create interactive, publication-quality charts. The most common approach is to use a Python library to generate the JavaScript and HTML code required by Highcharts, and then render that code in a web browser or a Jupyter Notebook.

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

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

The Core Concept

The workflow is generally:

  1. In Python: Use a library to define your chart's data, title, series, axes, etc.
  2. The Library: Generates the necessary JavaScript and HTML code.
  3. In the Browser/Jupyter: The generated code is executed, displaying the interactive Highcharts chart.

Method 1: highcharts-for-python (Recommended for most users)

This is the most direct and feature-rich library. It's a Python wrapper that mirrors the Highcharts API, making it very intuitive for those familiar with Highcharts.

Installation

First, install the library:

Python如何实现Highcharts动态图表?-图2
(图片来源网络,侵删)
pip install highcharts-for-python

Basic Example: Line Chart

This example shows how to create a simple line chart and display it in a Jupyter Notebook.

# Import necessary classes
from highcharts_core.chart import Chart
from highcharts_core.options import series
from highcharts_core.options import titles
# 1. Prepare your data
x_data = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
y_data = [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
# 2. Define the chart series
line_series = series.Line()
line_series.data = y_data
line_series.name = 'Sales 2025'
# 3. Configure the chart options
my_chart = Chart()
my_chart.title = titles.Title(text='Monthly Sales Data')
my_chart.x_axis.categories = x_data
my_chart.add_series(line_series)
# 4. Display the chart in Jupyter Notebook
# This will render the chart directly in the output cell.
my_chart.display()

When you run this in a Jupyter Notebook, you'll get an interactive chart.

Example: Bar Chart with Multiple Series

You can easily combine different chart types and add more series.

from highcharts_core.chart import Chart
from highcharts_core.options import series
from highcharts_core.options import titles
# Data
categories = ['Product A', 'Product B', 'Product C', 'Product D']
sales_q1 = [120, 200, 150, 80]
sales_q2 = [150, 230, 180, 100]
# Create the chart object
chart = Chart()
chart.title = titles.Title(text='Quarterly Sales Comparison')
# Set categories on the x-axis
chart.x_axis.categories = categories
# Create the first series (Q1 Sales)
bar_series_q1 = series.Column()
bar_series_q1.name = 'Q1 Sales'
bar_series_q1.data = sales_q1
# Create the second series (Q2 Sales)
bar_series_q2 = series.Column()
bar_series_q2.name = 'Q2 Sales'
bar_series_q2.data = sales_q2
# Add series to the chart
chart.add_series(bar_series_q1)
chart.add_series(bar_series_q2)
# Display the chart
chart.display()

Exporting to a File

You can also save the chart as a standalone HTML file to open in any browser.

# ... (use the chart object from the previous example) ...
# Export to an HTML file
chart.export_html('my_bar_chart.html')
print("Chart saved to my_bar_chart.html")

Method 2: py-highcharts (Simpler, for basic charts)

This library is simpler and focuses on generating the JavaScript dictionary directly. It's a good choice for quick and simple charts.

Installation

pip install py-highcharts

Example

from py_highcharts import Highchart
# 1. Initialize the chart
H = Highchart()
# 2. Add data
H.set_options('title', {'text': 'My First Python Chart'})
H.set_options('xAxis', {'categories': ['A', 'B', 'C', 'D', 'E']})
H.set_options('yAxis', {'title': {'text': 'Values'}})
# 3. Add a series
data = [1, 2, 3, 4, 5]
H.add_data_set(data, 'line', 'My Data Series')
# 4. Display in Jupyter
# In Jupyter, just call the object to display it.
H

Method 3: Plotly (plotly) - The "Highcharts Alternative"

It's important to know that Plotly is an extremely popular Python library for creating interactive charts. While it doesn't use Highcharts, it serves the same purpose and is often mentioned in the same breath.

The key difference is that Plotly has its own JavaScript rendering engine, whereas highcharts-for-python specifically generates Highcharts-compatible code.

Why choose Plotly?

  • All-in-one ecosystem: Part of a larger suite (Dash for web apps, ORCA for static images).
  • Wide range of chart types: Excellent for scientific and statistical charts.
  • Very active community.

Example with Plotly

pip install plotly
import plotly.express as px
# Data
df = px.data.iris() # Plotly includes sample datasets
# Create the chart
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
                 title="Iris Sepal Length vs. Width")
# Display the chart
# In Jupyter, Plotly charts display automatically.
fig.show()

Method 4: Manual Generation (For full control)

If you need ultimate flexibility or want to integrate Highcharts into a larger web application framework (like Flask or Django), you can generate the JavaScript code yourself using Python's f-strings or template engines.

This gives you full control over the HTML structure and the JavaScript options.

Example

import json
# 1. Define chart data and options as Python dictionaries
chart_data = [1, 2, 3, 4, 5]
chart_options = {
    'chart': {
        'type': 'line',
        'zoomType': 'x'
    },: {
        'text': 'Manually Generated Chart'
    },
    'xAxis': {
        'categories': ['Point 1', 'Point 2', 'Point 3', 'Point 4', 'Point 5']
    },
    'yAxis': {
        'title': {
            'text': 'Value'
        }
    },
    'series': [{
        'name': 'Series 1',
        'data': chart_data
    }]
}
# 2. Convert options to a JSON string
options_json = json.dumps(chart_options)
# 3. Create the final HTML/JS string
html_output = f"""
<!DOCTYPE html>
<html>
<head>Highcharts from Python</title>
    <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
    <div id="chart-container" style="width: 800px; height: 400px; margin: 0 auto;"></div>
    <script>
        Highcharts.chart('chart-container', {options_json});
    </script>
</body>
</html>
"""
# 4. Save to a file
with open('manual_chart.html', 'w') as f:
    f.write(html_output)
print("Chart saved to manual_chart.html")

Summary and Recommendation

Method Best For Pros Cons
highcharts-for-python Most users, Jupyter users, data scientists. High-fidelity to Highcharts API, great documentation, easy export. Requires an extra library installation.
py-highcharts Quick, simple charts. Very simple and lightweight. Less feature-rich, fewer updates.
plotly Interactive data science, web apps (Dash). All-in-one ecosystem, huge community, great for stats. Not Highcharts, different look/feel.
Manual Full control, web frameworks (Flask/Django). Ultimate flexibility, no dependencies. More verbose, requires JavaScript knowledge.

For anyone starting out or who needs a faithful Python representation of Highcharts, highcharts-for-python is the clear winner. It's powerful, easy to use, and integrates perfectly with the Jupyter Notebook environment.

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