, ,

Visualize and Analyze with Python and Next.js

Posted by

Let’s create a Next.js application that consumes and displays analyzed data from a Python backend. We’ll include graphs (using a library like Chart.js) and tables to present the data, and we’ll ensure the code is SEO-optimized.

Plan

  1. Setup Python Backend:
  • Create a Flask API to serve analyzed data.
  • Example endpoint to fetch data.
  1. Setup Next.js Frontend:
  • Fetch data from the Python backend.
  • Use Chart.js for graphs.
  • Use a table component to display data.
  • SEO optimization using Next.js features.

Step 1: Python Backend

# app.py

from flask import Flask, jsonify
import pandas as pd
import numpy as np

app = Flask(__name__)

# Simulate data analysis
def analyze_data():
    data = {
        'category': ['A', 'B', 'C', 'D'],
        'values': [23, 45, 56, 78]
    }
    df = pd.DataFrame(data)
    return df

@app.route('/api/data', methods=['GET'])
def get_data():
    df = analyze_data()
    result = df.to_dict(orient='records')
    return jsonify(result)

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

Step 2: Next.js Frontend

Directory Structure

/my-nextjs-app
├── components
│   ├── BarChart.js
│   ├── DataTable.js
├── pages
│   ├── index.js
├── public
│   ├── styles
│       ├── globals.css
├── package.json

Install Dependencies

npx create-next-app my-nextjs-app
cd my-nextjs-app
npm install chart.js react-chartjs-2 axios

BarChart Component

// components/BarChart.js

import { Bar } from 'react-chartjs-2';

const BarChart = ({ data }) => {
    const chartData = {
        labels: data.map(d => d.category),
        datasets: [
            {
                label: 'Values',
                data: data.map(d => d.values),
                backgroundColor: 'rgba(75, 192, 192, 0.6)',
            }
        ]
    };

    return <Bar data={chartData} />;
};

export default BarChart;

DataTable Component

// components/DataTable.js

const DataTable = ({ data }) => (
    <table>
        <thead>
            <tr>
                <th>Category</th>
                <th>Values</th>
            </tr>
        </thead>
        <tbody>
            {data.map((item, index) => (
                <tr key={index}>
                    <td>{item.category}</td>
                    <td>{item.values}</td>
                </tr>
            ))}
        </tbody>
    </table>
);

export default DataTable;

Home Page

// pages/index.js

import axios from 'axios';
import { useEffect, useState } from 'react';
import BarChart from '../components/BarChart';
import DataTable from '../components/DataTable';
import Head from 'next/head';

export default function Home() {
    const [data, setData] = useState([]);

    useEffect(() => {
        async function fetchData() {
            const result = await axios.get('http://127.0.0.1:5000/api/data');
            setData(result.data);
        }
        fetchData();
    }, []);

    return (
        <div>
            <Head>
                <title>Analyzed Data</title>
                <meta name="description" content="Visualize and analyze data using Next.js and Python." />
            </Head>
            <h1>Analyzed Data</h1>
            <BarChart data={data} />
            <DataTable data={data} />
        </div>
    );
}

Global Styles

/* public/styles/globals.css */

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

h1 {
    text-align: center;
    margin: 20px 0;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
}

th, td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: center;
}

th {
    background-color: #f2f2f2;
}

SEO Optimization

  • Title and Meta Tags: Use next/head to add a title and meta description.
  • Static Site Generation (SSG): For static data, use getStaticProps.

Final Thoughts

This setup ensures a smooth interaction between a Python backend for data analysis and a Next.js frontend for data visualization. Chart.js and a simple table component allow for clear and informative data presentation. SEO is handled using Next.js features like next/head.

One response

  1. Ashleyt Avatar
    Ashleyt

Leave a Reply

Your email address will not be published. Required fields are marked *