杰瑞科技汇

echarts ajax Python

Of course! This is a very common and powerful combination for creating dynamic, data-driven visualizations. Here’s a comprehensive guide on how to connect a Python backend (using Flask) to an ECharts frontend via AJAX.

echarts ajax Python-图1
(图片来源网络,侵删)

We'll build a simple web application that:

  1. A Python Flask server provides data from a Python list.
  2. An HTML page with ECharts displays a bar chart.
  3. When the page loads, JavaScript sends an AJAX request to the Python server.
  4. The Python server responds with the data in JSON format.
  5. ECharts uses this JSON data to render the chart.

The Core Concept

The communication flow looks like this:

  1. Frontend (Browser): An HTML page loads. A <script> tag runs an AJAX request (using fetch) to a specific URL on your Python server (e.g., /get-data).
  2. Backend (Python/Flask): The Flask app listens for requests to /get-data. When it receives one, it prepares the data (e.g., from a list, a database, or a file) and sends it back as a JSON response.
  3. Frontend (Browser): The fetch function receives the JSON data. A callback function then passes this data to the ECharts instance, telling it to update and render the chart.

Step-by-Step Implementation

Step 1: Project Setup

First, make sure you have Python and pip installed. Then, create a project directory and install Flask.

# Create a project folder
mkdir echarts-python-ajax
cd echarts-python-ajax
# Create a virtual environment (recommended)
python -m venv venv
# On Windows:
# venv\Scripts\activate
# On macOS/Linux:
# source venv/bin/activate
# Install Flask
pip install Flask

Your project structure should look like this:

echarts ajax Python-图2
(图片来源网络,侵删)
echarts-python-ajax/
├── venv/
├── app.py             # Our Python Flask server
└── templates/
    └── index.html     # Our HTML page with ECharts

Step 2: The Python Backend (app.py)

This script will define our web server and the data endpoint.

# app.py
from flask import Flask, jsonify, render_template
app = Flask(__name__)
# 1. Sample data in Python
# In a real application, this could come from a database, an API, or a file.
sales_data = {
    'categories': ['Shirts', 'Cardigans', 'Chiffons', 'Pants', 'Heels', 'Socks'],
    'values': [5, 20, 36, 10, 10, 20]
}
@app.route('/')
def index():
    """Serves the main HTML page."""
    return render_template('index.html')
@app.route('/get-data')
def get_data():
    """
    An API endpoint that returns the sales data in JSON format.
    This is the target of our AJAX request.
    """
    # jsonify converts the Python dictionary to a JSON response
    return jsonify(sales_data)
if __name__ == '__main__':
    # Running on http://127.0.0.1:5000
    app.run(debug=True)

Step 3: The Frontend (templates/index.html)

This is the file that the user will see in their browser. It includes ECharts from a CDN and the JavaScript to fetch data and render the chart.

Create the templates directory and add the index.html file inside it.

<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">ECharts with Python Flask</title>
    <!-- 1. Include ECharts from a CDN -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f0f2f5; }
        #main { width: 800px; height: 500px; background-color: white; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
    </style>
</head>
<body>
    <!-- 2. Prepare a DOM container for the chart -->
    <div id="main"></div>
    <script>
        // 3. Initialize the echarts instance based on the prepared dom
        var myChart = echarts.init(document.getElementById('main'));
        // 4. Use the modern fetch API to get data from the Python backend
        fetch('/get-data')
            .then(response => {
                // Check if the request was successful
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // Parse the JSON data from the response
                return response.json();
            })
            .then(data => {
                // 5. Use the data to set the chart option
                var option = {
                    title: {
                        text: 'Sales Data from Python'
                    },
                    tooltip: {},
                    legend: {
                        data: ['Sales']
                    },
                    xAxis: {
                        data: data.categories
                    },
                    yAxis: {},
                    series: [{
                        name: 'Sales',
                        type: 'bar',
                        data: data.values,
                        itemStyle: {
                            color: '#3398DB'
                        }
                    }]
                };
                // 6. Set the option to the chart instance
                myChart.setOption(option);
            })
            .catch(error => {
                console.error('There was a problem with the fetch operation:', error);
                // Optionally display an error message on the page
                document.getElementById('main').innerHTML = '<h2 style="text-align:center; color:red;">Error loading chart data.</h2>';
            });
        // Optional: Make the chart responsive
        window.addEventListener('resize', function() {
            myChart.resize();
        });
    </script>
</body>
</html>

Step 4: Run the Application

  1. Make sure you are in your project's root directory (echarts-python-ajax/).
  2. Run the Flask app from your terminal:
    python app.py
  3. You will see output indicating the server is running:
     * Serving Flask app 'app'
     * Debug mode: on
     * Running on http://127.0.0.1:5000
    Press CTRL+C to quit
  4. Open your web browser and navigate to http://127.0.0.1:5000.

You should see a bar chart populated with the data from your Python script!

echarts ajax Python-图3
(图片来源网络,侵删)

Going Further: A More Complex Example (Pandas)

In a real-world scenario, your data will likely be in a structured format like a CSV file. Let's enhance the example to use Pandas to read a CSV and send it to the frontend.

Install Pandas

pip install pandas

Create a CSV file

Create a file named sales.csv in your project root.

Month,Product,Sales
January,Widget A,150
January,Widget B,200
February,Widget A,180
February,Widget B,170
March,Widget A,220
March,Widget B,240

Update app.py

Now, we'll modify the Python code to read this CSV and transform it into a format ECharts can easily use (a "wide" format).

# app.py (updated)
import pandas as pd
from flask import Flask, jsonify, render_template
app = Flask(__name__)
# Read the CSV file into a pandas DataFrame
df = pd.read_csv('sales.csv')
# Pivot the data to get the desired format for ECharts
# Index by 'Month', columns are 'Product', values are 'Sales'
pivot_df = df.pivot(index='Month', columns='Product', values='Sales')
# Convert the pivot table to a dictionary
# .to_dict() with 'orient=list' creates a structure like:
# {'categories': ['January', 'February', 'March'], 'Widget A': [150, 180, 220], 'Widget B': [200, 170, 240]}
sales_data = pivot_df.to_dict(orient='list')
@app.route('/')
def index():
    return render_template('index.html')
@app.route('/get-data')
def get_data():
    return jsonify(sales_data)
if __name__ == '__main__':
    app.run(debug=True)

Update templates/index.html

We need to adjust the JavaScript to handle this new data structure, which has multiple data series.

<!-- templates/index.html (updated) -->
<!-- ... (head and body setup are the same) ... -->
<script>
    var myChart = echarts.init(document.getElementById('main'));
    fetch('/get-data')
        .then(response => response.json())
        .then(data => {
            // Prepare the series data dynamically from the response
            var series = Object.keys(data).filter(key => key !== 'categories').map(function(productName) {
                return {
                    name: productName,
                    type: 'line', // Using a line chart for this multi-series example
                    data: data[productName],
                    smooth: true
                };
            });
            var option = {
                title: {
                    text: 'Monthly Sales by Product'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: Object.keys(data).filter(key => key !== 'categories')
                },
                xAxis: {
                    type: 'category',
                    data: data.categories
                },
                yAxis: {
                    type: 'value'
                },
                series: series // Use the dynamically created series array
            };
            myChart.setOption(option);
        })
        .catch(error => {
            console.error('Error fetching data:', error);
            document.getElementById('main').innerHTML = '<h2 style="text-align:center; color:red;">Error loading chart data.</h2>';
        });
    window.addEventListener('resize', function() {
        myChart.resize();
    });
</script>
</body>
</html>

Now, run app.py again and refresh the page. You will see a line chart with two lines, one for each product, showing their sales over the months. This demonstrates how easily you can integrate powerful Python data processing libraries like Pandas with a dynamic frontend like ECharts.

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