How to Create a Simple Area Chart using Google Charts API
Submitted by nurhodelta_17 on Saturday, March 31, 2018 - 21:59.
Creating our Database
First, we are going to create our database which contains the sample data that we are going to present using Google Chart API in the form of area chart. I've included a .sql file in the downloadable of this tutorial which is a mysql database file. All you have to do is import the said file. If you have no idea on how to do this, please refer to my tutorial, How import .sql file to restore MySQL database. You should be able to create a database with tables named database.Creating the Presentation
Lastly, we create the page where we present the data using area chart. Create a new file, name it as index.php and paste the codes below.- <?php
- //connection
- $conn = new mysqli('localhost', 'root', '', 'database');
- ?>
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>How to Create a Simple Area Chart using Google Charts API</title>
- </head>
- <body>
- <div id="area_chart" style="width: 900px; height: 500px;"></div>
- <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([
- ['Year', 'Sales', 'Expenses'],
- <?php
- for($i = 2014; $i <= 2017; $i++){
- //sales
- $sql = "SELECT sum(sales) AS sum_sales FROM sales WHERE year(date) = '$i'";
- $sales_query = $conn->query($sql);
- $sales_row = $sales_query->fetch_assoc();
- //expense
- $sql = "SELECT sum(expenses) AS sum_expenses FROM expenses WHERE year(date) = '$i'";
- $expense_query = $conn->query($sql);
- $expense_row = $expense_query->fetch_assoc();
- //displaying the needed data
- echo '["'.$i.'", '.$sales_row['sum_sales'].', '.$expense_row['sum_expenses'].'],';
- }
- ?>
- //
- // ['2013', 1000, 400],
- // ['2014', 1170, 460],
- // ['2015', 660, 1120],
- // ['2016', 1030, 540]
- ]);
- var options = {
- title: 'Company Performance',
- hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
- vAxis: {minValue: 0}
- };
- var chart = new google.visualization.AreaChart(document.getElementById('area_chart'));
- chart.draw(data, options);
- }
- </script>
- </body>
- </html>
Add new comment
- 276 views