article

Wednesday, April 7, 2021

Python Flask Show Data on Google Pie Chart

Python Flask Show Data on Google Pie Chart

Pie charts are used to show percentage or proportional data and the percentage represented by each category is provided next to the corresponding slice of pie.


app.py
 
#app.py
from flask import Flask, render_template

app = Flask(__name__)
  
@app.route('/')
def google_pie_chart():
	data = {'Task' : 'Hours per Day', 'Work' : 22, 'Eat' : 4, 'Commute' : 6, 'Watching TV' : 5, 'Sleeping' : 15}
	return render_template('index.html', data=data)

if __name__ == "__main__":
    app.run()
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Python Flask Show Data on Google Pie 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([
			{% for key, value in data.items() %}
				{% if value is string %}
					['{{ key }}', '{{ value }}'],
				{% else %}
					['{{ key }}', {{ value }}],
				{% endif %}
			{% endfor %}
        ]);

        var options = {
          title: 'My Daily Activities',
          is3D: true,
		  //pieHole: 0.5
		  pieStartAngle: 100
		  /*slices: {  
			2: {offset: 0.2},
            3: {offset: 0.3}
          }*/
		  /*slices: {
            1: { color: 'transparent' }
          }*/
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
        chart.draw(data, options);
      }
    </script>
</head>
<body>
	<div style="margin: 10px 0 0 10px;width: 1000px">
		<h3>Python Flask Show Data on Google Pie Chart</h3>
		<div id="piechart_3d" style="width: 900px; height: 500px;"></div>
	</div>
</body>
</html>

Related Post