Full Code: React + Flask for Dynamic Matplotlib Visualizations
This application allows users to:
- Select a chart type (Bar Chart, Pie Chart, Histogram, etc.)
- Upload an Excel file or paste a dataset
- Send data to Flask backend, process it using Matplotlib, and return an image
- Display the visualization in React frontend
📌 Step 1: Install Required Dependencies
Backend (Flask
) Run the following in your Flask environment:
pip install flask flask-cors pandas matplotlib openpyxl
flask
→ Web framework
flask-cors
→ Allows frontend-backend communication
pandas
→ Reads Excel and CSV files
matplotlib
→ Generates visualizations
openpyxl
→ Reads Excel files
Frontend (React)
Inside your React project:
npm install axios
axios → Sends requests to the Flask backend
📌 Step 2: Backend (Flask)
Create a Flask app (app.py) to:
✅ Accept chart type & dataset (from text input or uploaded Excel file)
✅ Process data using pandas
✅ Generate Matplotlib visualizations
✅ Return an image to the frontend
🔧 app.py (Flask Backend)
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import pandas as pd
import matplotlib.pyplot as plt
import io
import os
app = Flask(__name__)
CORS(app) # Enable Cross-Origin Requests
UPLOAD_FOLDER = "uploads"
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
@app.route("/generate_chart", methods=["POST"])
def generate_chart():
try:
chart_type = request.form.get("chartType") # Get selected chart type
dataset_text = request.form.get("dataset") # Get dataset from textarea
file = request.files.get("file") # Get uploaded file
# Read data: From textarea (CSV format) or uploaded Excel file
if file:
df = pd.read_excel(file) # Read Excel file
elif dataset_text:
df = pd.read_csv(io.StringIO(dataset_text)) # Read CSV from textarea
else:
return jsonify({"error": "No dataset provided"}), 400
# Generate visualization based on selected chart type
plt.figure(figsize=(8, 6))
if chart_type == "barchart":
df.plot(kind="bar")
elif chart_type == "piechart":
df.iloc[:, 1].plot(kind="pie", labels=df.iloc[:, 0], autopct="%1.1f%%")
elif chart_type == "histogram":
df.hist()
else:
return jsonify({"error": "Invalid chart type"}), 400
# Save image and send it to frontend
img_path = os.path.join(UPLOAD_FOLDER, "chart.png")
plt.savefig(img_path)
plt.close()
return send_file(img_path, mimetype="image/png")
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
app.run(debug=True)
📌 Step 3: Frontend (React)
🔧 ChartUploader.js (React Component)
import React, { useState } from "react";
import axios from "axios";
const ChartUploader = () => {
const [chartType, setChartType] = useState("barchart");
const [dataset, setDataset] = useState("");
const [file, setFile] = useState(null);
const [chartImage, setChartImage] = useState(null);
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setErrorMessage("");
const formData = new FormData();
formData.append("chartType", chartType);
if (file) {
formData.append("file", file);
} else {
formData.append("dataset", dataset);
}
try {
const response = await axios.post("http://127.0.0.1:5000/generate_chart", formData, {
responseType: "blob",
});
// Convert the response blob into an image URL
const imageUrl = URL.createObjectURL(response.data);
setChartImage(imageUrl);
} catch (error) {
setErrorMessage(error.response?.data?.error || "Error generating chart");
} finally {
setLoading(false);
}
};
return (
<div style={{ textAlign: "center", padding: "20px" }}>
<h2>Upload Dataset and Generate Chart</h2>
<form onSubmit={handleSubmit} style={{ marginBottom: "20px" }}>
{/* Dropdown for Chart Type */}
<label>
Select Chart Type:
<select value={chartType} onChange={(e) => setChartType(e.target.value)} style={{ marginLeft: "10px" }}>
<option value="barchart">Bar Chart</option>
<option value="piechart">Pie Chart</option>
<option value="histogram">Histogram</option>
</select>
</label>
{/* Textarea for CSV Data Input */}
<div>
<textarea
rows="5"
cols="50"
placeholder="Paste CSV data here..."
value={dataset}
onChange={(e) => setDataset(e.target.value)}
style={{ marginTop: "10px", width: "80%" }}
/>
</div>
{/* File Upload for Excel */}
<div style={{ marginTop: "10px" }}>
<input type="file" accept=".xlsx, .xls" onChange={(e) => setFile(e.target.files[0])} />
</div>
<button type="submit" disabled={loading} style={{ marginTop: "10px", padding: "10px 15px", cursor: "pointer" }}>
{loading ? "Generating Chart..." : "Generate Chart"}
</button>
</form>
{/* Error Message */}
{errorMessage && <p style={{ color: "red" }}>{errorMessage}</p>}
{/* Display Generated Chart */}
{chartImage && (
<div>
<h3>Generated Chart:</h3>
<img src={chartImage} alt="Generated Chart" style={{ maxWidth: "100%", height: "auto" }} />
</div>
)}
</div>
);
};
export default ChartUploader;
📌 Step 4: Integrate into React App
Modify App.js to include the ChartUploader component.
🔧 App.js
import React from "react";
import ChartUploader from "./ChartUploader";
function App() {
return (
<div>
<h1>Data Visualization App</h1>
<ChartUploader />
</div>
);
}
export default App;
📌 Step 5: Run the Application
Runs the Flask API on http://127.0.0.1:5000/.
Frontend (React)
npm start
Runs the React app on http://localhost:3000/.
🎯 How the App Works
Select a chart type (Bar Chart, Pie Chart, Histogram).
Upload an Excel file or paste CSV data into the textarea.
Click "Generate Chart".
Flask processes the data and generates a chart using Matplotlib.
The chart is sent back as an image and displayed in React.
Top comments (0)