You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AJAX在单个Highcharts图表中展示两个Python函数的数值?

Nice job getting a single real-time HighCharts setup running with Flask and Python! Merging two data streams from separate Python functions into one chart is totally doable—here's how to adjust your setup step by step.

Backend: Combine Data from Both Functions

Instead of having two separate routes for each function, create a single endpoint that fetches data from both functions and returns them together as JSON. This reduces redundant AJAX requests and keeps your data sync'd:

from flask import Flask, jsonify
import time
# Replace these with your actual Python functions
def fetch_data_func1():
    # Example: return a dynamic value from your first function
    return round(time.time() % 100, 2)

def fetch_data_func2():
    # Example: return a dynamic value from your second function
    return round((time.time() + 50) % 100, 2)

app = Flask(__name__)

@app.route('/get_combined_data')
def get_combined_data():
    # Pull data from both functions
    data1 = fetch_data_func1()
    data2 = fetch_data_func2()
    # Return as JSON with both values (plus timestamp for X-axis)
    return jsonify({
        "value1": data1,
        "value2": data2,
        "timestamp": time.time() * 1000  # Convert to milliseconds for HighCharts
    })

if __name__ == '__main__':
    app.run(debug=True)

Frontend: Update HighCharts to Handle Two Series

Modify your HTML/JS to initialize a chart with two data series, then update both series each time you pull new data via AJAX:

<!DOCTYPE html>
<html>
<head>
    <title>Dual Stream Real-Time Chart</title>
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
    <div id="real-time-chart" style="width: 90%; height: 500px; margin: 0 auto;"></div>

    <script>
        // Initialize the HighChart with TWO empty series
        const chart = Highcharts.chart('real-time-chart', {
            chart: { type: 'line', animation: false }, // Disable animation for smoother updates
            title: { text: 'Real-Time Data from Two Python Functions' },
            xAxis: {
                type: 'datetime',
                title: { text: 'Time' }
            },
            yAxis: {
                title: { text: 'Values' },
                min: 0,
                max: 100 // Adjust based on your data range
            },
            tooltip: {
                formatter: function() {
                    return `<b>${this.series.name}</b><br/>
                            ${Highcharts.dateFormat('%H:%M:%S', this.x)}<br/>
                            Value: ${this.y}`;
                }
            },
            legend: { enabled: true },
            series: [
                { name: 'Function 1 Output', data: [] },
                { name: 'Function 2 Output', data: [] }
            ]
        });

        // Set up interval to pull and update data
        setInterval(() => {
            $.ajax({
                url: '/get_combined_data',
                cache: false,
                success: (response) => {
                    const x = response.timestamp; // Use backend timestamp for sync
                    const y1 = response.value1;
                    const y2 = response.value2;

                    // Add new point to first series, remove oldest if over 20 points
                    chart.series[0].addPoint([x, y1], true, chart.series[0].data.length > 20);
                    // Add new point to second series, same cleanup logic
                    chart.series[1].addPoint([x, y2], true, chart.series[1].data.length > 20);
                }
            });
        }, 1000); // Update every 1 second (adjust as needed)
    </script>
</body>
</html>

Key Notes to Keep in Mind

  • Data Sync: By fetching both values in one AJAX call, you ensure the two data points are timestamped at the same moment, avoiding misalignment on the chart.
  • Data Cleanup: The third parameter in addPoint (chart.series[0].data.length > 20) automatically removes the oldest data point once you have more than 20 entries—this keeps your chart performant and uncluttered. Adjust the number based on how much historical data you want to show.
  • Customization: Tweak the chart type (e.g., column instead of line), Y-axis range, or tooltip formatting to match your needs.

内容的提问来源于stack exchange,提问作者Tia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:27:34