Open In App

Google Pie Chart using Flask

Last Updated : 08 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to show data on a Google line chart using Python Flask. Python Flask is a popular web framework that allows us to create web applications in Python. Firstly, we will install Flask using the following command:

pip install Flask

What is Google Line Chart

Google line chart is a powerful visualization tool that allows us to represent data in a line chart format. With the help of the Google Charts API, we can easily create line charts on our web applications.

Show Data on Google Pie Chart using Python Flask

We need to create a Flask application folder. We will create a basic Flask application to display a line chart on a web page.

 

Step 1: Create a virtual environment.

Step 2: Create a  new directory called “templates“, in this folder create an index.html file and add the below code:

HTML




<!DOCTYPE html>
<html>
<head>
   <title>Google Line Chart</title>
   <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   <script type="text/javascript">
       google.charts.load('current', {'packages':['corechart']});
       google.charts.setOnLoadCallback(drawChart);
  
       function drawChart() {
           var data = google.visualization.arrayToDataTable({{data|safe}});
           var options = {
               title: 'Sales per Year',
               curveType: 'function',
               legend: { position: 'bottom' },
               series: {
                  0: { color: "#008000" },
              }
           };
           var chart = new google.visualization.LineChart(document.getElementById('chart'));
           chart.draw(data, options);
       }
   </script>
</head>
<body>
   <div id="chart"></div>
</body>
</html>


Step 3: Create a new Python file called “app.py“.

Step 4: Now, we start a new Flask application after importing the Flask module. The root URL (‘/’) is then used to establish a route for our application. The data we wish to show on our line chart is defined in the index function. Each inner list in the data’s list of lists represents a row of information. The X-axis value is represented by the first member in each inner list, while the Y-axis value is represented by the second element.

Python3




from flask import Flask, render_template
  
app = Flask(__name__)
  
  
@app.route('/')
def index():
    data = [
        ['Year', 'Sales'],
        ['2015', 1000],
        ['2016', 1170],
        ['2017', 660],
        ['2018', 1030]
    ]
    return render_template('index.html', data=data)
  
  
if __name__ == '__main__':
    app.run()


Output:

Google Pie Chart using Flask

Chart

Related Articles: Show Data on Google Pie Chart using Python Flask



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads