Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Pandas
  • Numpy
  • Seaborn
  • Ploty
  • Data visualization
  • Data Analysis
  • Power BI
  • Tableau
  • Machine Learning
  • Deep Learning
  • NLP
  • Computer Vision
  • Data Science for Beginners
  • Data Science interview questions
  • Data analysis interview questions
  • NLP Interview questions
Open In App
Next Article:
Create Scatter Charts in Matplotlib using Flask
Next article icon

Create Scatter Charts in Matplotlib using Flask

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to create charts in Matplotlib with Flask. We will discuss two different ways how we can create Matplotlib charts in Flask and present it on an HTML webpage with or without saving the plot using Python.

File structure

Create Charts in Matplotlib with flask
 

Create and Save the Plot in the Static Directory

Here, We first created a get_plot() function which generates the Matplotlib plot and returns the plot object. Python's Numpy library generates random data for this plot. It is not necessary to import if you are defining your own data. The root URL ('/') first calls this function to get the plot object. It then saves this plot object as 'plot.png' under the images folder present inside the static directory. This is the default location defined by Flask for static files like images, CSS, JS, etc.  The final step is to render the below HTML script which reads the image file from the directory and renders it to the web browser as shown in the output image.

Python3
# Importing required functions  import numpy as np import matplotlib.pyplot as plt from flask import Flask, render_template   # Flask constructor  app = Flask(__name__)  # Generate a scatter plot and returns the figure def get_plot():     data = {         'a': np.arange(50),         'c': np.random.randint(0, 50, 50),         'd': np.random.randn(50)     }     data['b'] = data['a'] + 10 * np.random.randn(50)     data['d'] = np.abs(data['d']) * 100      plt.scatter('a', 'b', c='c', s='d', data=data)     plt.xlabel('X label')     plt.ylabel('Y label')     return plt  # Root URL @app.get('/') def single_converter():     # Get the matplotlib plot      plot = get_plot()      # Save the figure in the static directory      plot.savefig(os.path.join('static', 'images', 'plot.png'))      return render_template('matplotlib-plot1.html')  # Main Driver Function  if __name__ == '__main__':     # Run the application on the local development server      app.run(debug=True) 

Save the HTML file as 'matplotlib-plot1.html' under the templates folder in the root directory.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <title>Matplotlib Plot</title> </head>  <body>     <h1>How to Create Charts in Matplotlib with flask - Example 1</h1>     <img src="{{ url_for('static', filename='images/plot.png') }}"> </body>  </html> 

Output:

Create Charts in Matplotlib with flask
Example 1 - Output

Generating a Base64 I/O String of the Plot

We will generate the base64 I/O) string format for the image and pass this to the template to render the plot. Here, We first created a get_plot() function which generates the Matplotlib plot and returns the plot object. Python's Numpy library generates random data for this plot. It is not necessary to import if you are defining your own data. The root URL ('/') first calls this function to get the plot object. It then creates a Base64 I/O equivalent format of the string using python's built-in 'io' and 'base64' modules. The final step is to render the below HTML script and also pass this string to the template. The template reads the image file using the string that is passed to it.

Python
# Importing required functions from flask import Flask, render_template import matplotlib.pyplot as plt import os import numpy as np import matplotlib matplotlib.use('Agg')   # Flask constructor app = Flask(__name__)  # Generate a scatter plot and returns the figure def get_plot():      data = {         'a': np.arange(50),         'c': np.random.randint(0, 50, 50),         'd': np.random.randn(50)     }      data['b'] = data['a'] + 10 * np.random.randn(50)     data['d'] = np.abs(data['d']) * 100      plt.scatter('a', 'b', c='c', s='d', data=data)     plt.xlabel('X label')     plt.ylabel('Y label')      return plt  # Root URL @app.get('/') def single_converter():     # Get the matplotlib plot     plot = get_plot()      # Save the figure in the static directory     plot.savefig(os.path.join('static', 'images', 'plot.png'))      # Close the figure to avoid overwriting     plot.close()     return render_template('matplotlib-plot1.html')  # Main Driver Function if __name__ == '__main__':     # Run the application on the local development server     app.run(debug=True) 

Save the HTML file as 'matplotlib-plot2.html' under the templates folder in the root directory.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <title>Matplotlib Plot</title> </head>  <body>     <h1>How to Create Charts in Matplotlib with flask - Example 2</h1>     <img src="data:image/png;base64,{{ s }}"> </body>  </html> 

Output:

Create Charts in Matplotlib with flask
Example 2 - Output

Related Articles: How to Add Graphs to Flask apps


Next Article
Create Scatter Charts in Matplotlib using Flask

A

apathak092
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Technical Scripter 2022
  • Python-matplotlib
  • Python Flask
Practice Tags :
  • python

Similar Reads

    Generate a Heatmap in MatPlotLib Using a Scatter Dataset
    Heatmaps are a powerful visualization tool that can help you understand the density and distribution of data points in a scatter dataset. They are particularly useful when dealing with large datasets, as they can reveal patterns and trends that might not be immediately apparent from a scatter plot a
    5 min read
    How to create a Scatter Plot with several colors in Matplotlib?
    Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. In this article, we w
    3 min read
    Create lollipop charts with Pandas and Matplotlib
    In this article, we will create Lollipop Charts. They are nothing but a variation of the bar chart in which the thick bar is replaced with just a line and a dot-like “o” (o-shaped) at the end. Lollipop Charts are preferred when there are lots of data to be represented that can form a cluster when re
    4 min read
    Python | Basic Gantt chart using Matplotlib
    Prerequisites : Matplotlib IntroductionIn this article, we will be discussing how to plot a Gantt Chart in Python using Matplotlib.A Gantt chart is a graphical depiction of a project schedule or task schedule (In OS). It's is a type of bar chart that shows the start and finish dates of several eleme
    3 min read
    Scatter plot in Plotly using graph_objects class
    Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences