杰瑞科技汇

如何用Python实现Highcharts图表?

Of course! Using Highcharts with Python is a very common task, but it's important to understand that Highcharts is a JavaScript library, not a Python one.

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

Therefore, the process involves using a Python library to generate the JavaScript and HTML code required to render the chart. The most popular and recommended library for this is highcharts.

Here’s a complete guide covering:

  1. The Core Concept: How Python and Highcharts work together.
  2. Installation: How to install the necessary Python library.
  3. Basic Examples: Creating your first charts (Line, Bar, Pie).
  4. Advanced Features: Adding options, titles, and exporting.
  5. Alternative Methods: Other ways to use Highcharts with Python.
  6. Final Example: A complete, interactive HTML file.

The Core Concept

Think of it like this:

  1. Python (The Backend): You use a Python library (highcharts) to define your chart's data, type, title, colors, etc. This library acts as a translator.
  2. The highcharts Library: This library takes your Python objects (lists, dictionaries) and converts them into a valid JavaScript Highcharts configuration object.
  3. HTML/JavaScript (The Frontend): This generated JavaScript code is then embedded into an HTML file. When you open this file in a web browser, the browser's JavaScript engine executes the code and renders the interactive chart.

Installation

The most straightforward way is to use the highcharts-for-python library.

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

You'll also need a web browser to view the final HTML output.


Basic Examples

Let's create some simple charts. The general workflow is:

  1. Import the necessary class from the highcharts library.
  2. Create an instance of the chart class.
  3. Set properties like title, x_axis, y_axis, series, etc.
  4. Call the .to_html_file() method to save the chart as an HTML file.

Example 1: A Simple Line Chart

This is the "Hello, World!" of charts.

from highcharts import Highchart
# 1. Create a Highchart object
H = Highchart()
# 2. Add the data for the series
data_series = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
H.add_data_set(data_series, 'line', 'My First Line')
# 3. Set the chart title
H.set_options('title', {'text': 'My First Highchart Chart'})
# 4. Export to an HTML file
H.to_html_file('line_chart.html')
print("Chart saved to line_chart.html")

After running this, you'll have a line_chart.html file. Open it in your browser to see the chart.

Example 2: A Bar Chart

from highcharts import Highchart
H = Highchart()
# Data can be a list of lists
categories = ['Apples', 'Bananas', 'Oranges']
data_values = [12, 19, 8]
H.add_data_set(data_values, 'bar', 'Fruit Consumption', categories=categories)
H.set_options('title', {'text': 'Fruit Consumption Chart'})
H.set_options('xAxis', {'title': {'text': 'Fruit Type'}})
H.set_options('yAxis', {'title': {'text': 'Amount'}})
H.to_html_file('bar_chart.html')
print("Chart saved to bar_chart.html")

Example 3: A Pie Chart

Pie charts use slightly different options, like data instead of series and pointFormat for tooltips.

from highcharts import Highchart
H = Highchart()
# Data for a pie chart is a list of dictionaries
data_pie = [
    {'name': 'Chrome', 'y': 60},
    {'name': 'Firefox', 'y': 25},
    {'name': 'Edge', 'y': 10},
    {'name': 'Safari', 'y': 5}
]
# Use 'pie' as the chart type and pass the data directly
H.set_options('chart', {'type': 'pie'})
H.set_options('title', {'text': 'Browser Usage 2025'})
H.set_options('tooltip', {'pointFormat': '{series.name}: <b>{point.percentage:.1f}%</b>'})
H.set_options('plotOptions', {
    'pie': {
        'allowPointSelect': True,
        'cursor': 'pointer',
        'dataLabels': {
            'enabled': True,
            'format': '<b>{point.name}</b>: {point.percentage:.1f} %'
        }
    }
})
H.add_data_set(data_pie, 'pie', 'Browser Share')
H.to_html_file('pie_chart.html')
print("Chart saved to pie_chart.html")

Advanced Features

You can customize almost every aspect of the chart. The set_options method is your best friend.

Adding Multiple Series and Subtitle

from highcharts import Highchart
import pandas as pd
H = Highchart()
# Sample data
data_sales = [150, 230, 224, 218, 135, 147, 260]
data_profit = [50, 80, 70, 65, 30, 40, 90]
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']
# Add two series
H.add_data_set(data_sales, 'line', 'Total Sales', marker={'symbol': 'square'})
H.add_data_set(data_profit, 'line', 'Net Profit', marker={'symbol': 'diamond'})
# Set multiple options
H.set_options('title', {'text': 'Sales and Profit Analysis (H1 2025)'})
H.set_options('subtitle', {'text': 'Data for the first half of the year'})
H.set_options('xAxis', {'categories': months})
H.set_options('yAxis', {'title': {'text': 'Amount (in USD)'}})
# Add a legend
H.set_options('legend', {'layout': 'vertical', 'align': 'right', 'verticalAlign': 'middle'})
H.to_html_file('multi_line_chart.html')

Exporting to JSON

If you want to use the chart in a different environment (like a JavaScript web framework), you can export the configuration as a JSON string.

from highcharts import Highchart
H = Highchart()
H.add_data_set([1, 2, 3], 'line')
H.set_options('title', {'text': 'JSON Export Example'})
# Get the JavaScript options as a JSON string
chart_json = H.get_options()
print(chart_json)
# You can save this to a file if needed
# with open('chart_config.json', 'w') as f:
#     f.write(chart_json)

Alternative Methods

While highcharts-for-python is the most direct, other approaches exist:

A. Generating HTML Strings Manually

You can write Python code to construct the HTML string yourself. This gives you full control but is more error-prone and tedious.

html_content = f"""
<!DOCTYPE html>
<html>
<head>Manual Chart</title>
    <script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
    <div id="container" style="width: 100%; height: 400px;"></div>
    <script>
        Highcharts.chart('container', {{
            chart: {{
                type: 'bar'
            }},
            title: {{
                text: 'Manually Generated Chart'
            }},
            xAxis: {{
                categories: ['Cat1', 'Cat2', 'Cat3']
            }},
            yAxis: {{
                title: {{
                    text: 'Value'
                }}
            }},
            series: [{{
                name: 'Series 1',
                data: [1, 2, 3]
            }}]
        }});
    </script>
</body>
</html>
"""
with open('manual_chart.html', 'w') as f:
    f.write(html_content)
print("Manual HTML chart saved.")

B. Using pandas and mplcharts

If you're already using pandas for data analysis, the mplcharts library can be very convenient. It allows you to use a familiar matplotlib-like syntax to generate Highcharts.

pip install mplcharts pandas
import pandas as pd
from mplcharts import HighchartPlot
# Create a pandas DataFrame
data = {'months': ['Jan', 'Feb', 'Mar', 'Apr'],
        'sales': [100, 150, 200, 180],
        'costs': [80, 100, 120, 110]}
df = pd.DataFrame(data)
# Create the plot object
plot = HighchartPlot()
# Plot the DataFrame
# mplcharts automatically uses the index for the x-axis
# and other columns for y-axes
plot.plot(df[['sales', 'costs']], kind='line')
# Save to HTML
plot.save('mplcharts_example.html')

Complete Example: A Jupyter Notebook Workflow

A very common use case is generating charts directly in a Jupyter Notebook.

  1. Install ipython and notebook if you haven't already.
  2. Install highcharts.
  3. In a Jupyter cell, run:
from highcharts import Highchart
# This will make the chart render inline in the notebook
H = Highchart()
data = {
    'chart': {'type': 'column'},: {'text': 'Monthly Average Temperature'},
    'subtitle': {'text': 'Source: WorldClimate.com'},
    'xAxis': {'categories': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']},
    'yAxis': {'min': -10, 'title': {'text': 'Temperature (°C)'}},
    'tooltip': {
        'headerFormat': '<span style="font-size:10px">{point.key}</span><table>',
        'pointFormat': '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                       '<td style="padding:0"><b>{point.y:.1f} °C</b></td></tr>',
        'footerFormat': '</table>',
        'shared': True,
        'useHTML': True
    },
    'plotOptions': {
        'column': {
            'pointPadding': 0.2,
            'borderWidth': 0
        }
    },
    '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]
    }, {
        'name': 'New York',
        'data': [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
    }]
}
# The set_options method can take a full dictionary
H.set_options(data)
# To display in a notebook, you can just output the object
# or use its _repr_html_ method
H

This will render the interactive chart directly in your notebook output.

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