You are on page 1of 30

Unit: 3 Visualizing Data Programmatically

Canvas :
To draw a straight line on a canvas, use the following methods:
moveTo(x,y) - defines the starting point of the line
lineTo(x,y) - defines the ending point of the line
To actually draw the line, you must use one of the "ink" methods, like stroke().

setLineDash([ ]) : Sets the pattern for drawing dashed lines. The argument that you give to the
function should be an array that contains numbers that indicate the desired dash setting that includes
tha length of ths dash and gap between two dash.

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="2000" height="1000" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.moveTo(50,50);
ctx.lineTo(200,100);
ctx.stroke();
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="2000" height="1000" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.setLineDash([5]); //To draw Dashed Line
ctx.moveTo(50,50);
ctx.lineTo(200,100);
ctx.stroke();
</script>
</body>
</html>
To draw a rectangle on a canvas, use the following methods:

strokeRect(): draws a rectangle (no fill). The default color of the stroke is black. Use the
strokeStyle property to set a color, gradient, or pattern to style the stroke.
Syntax: context.strokeRect(x,y,width,height);

fillRect(): method draws a "filled" rectangle. The default color of the fill is black. Use the fillStyle
property to set a color, gradient, or pattern used to fill the drawing.
Syntax: context.fillRect(x,y,width,height);

clearRect(): method clears the specified pixels within a given rectangle.


Syntax: context.clearRect(x,y,width,height);

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid black;">
Your browser does not support the canvas element.
</canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// Red empty rectangle


ctx.strokeStyle = "red";
ctx.strokeRect(5, 5, 100, 100);
ctx.stroke();

// Green filled rectangle


ctx.fillStyle = "green";
ctx.fillRect(150, 5, 100, 100);
ctx.stroke();

// Blue empty rectangle with dashed line


ctx.setLineDash([5]); //Dashed border
ctx.strokeStyle="blue";
ctx.strokeRect(300, 5, 100, 100);

// Clear Rectangle within Green Rectangle


ctx.clearRect(170, 10, 50, 50);

</script>
</body>
</html>
arc(): method creates an arc/curve (used to create circles, or parts of circles).
To create a circle with arc(): Set start angle to 0 and end angle to 2*Math.PI.
Use the stroke() or the fill() method to actually draw the arc on the canvas.
Syntax: context.arc(x, y, r, sAngle, eAngle, counterclockwise);
Where,
x - The x-coordinate of the center of the circle
y - The y-coordinate of the center of the circle
r - The radius of the circle
sAngle - The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
eAngle - The ending angle, in radians
counterclockwise - Optional. Specifies whether the drawing should be counterclockwise or
clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.

The beginPath() method begins a path, or resets the current path.

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Empty Circle
ctx.beginPath();
ctx.arc(80, 80, 40, 0, 2 *Math.PI);
ctx.strokeStyle="green";
ctx.stroke();
// Filled Circle
ctx.beginPath();
ctx.arc(200, 80, 40, 0, 2*Math.PI);
ctx.fillStyle="blue";
ctx.fill()
// Half Circle
ctx.beginPath();
ctx.arc(300, 80, 40, 0, Math.PI);
ctx.strokeStyle="red";
ctx.stroke();
// 1/4th Part of Circle
ctx.beginPath();
ctx.arc(80, 200, 40, 0, 0.5*Math.PI);
ctx.strokeStyle="magenta";
ctx.stroke();
// 3/4th Part of Circle
ctx.beginPath();
ctx.arc(200, 200, 40, 0, 1.5*Math.PI);
ctx.strokeStyle="green";
ctx.stroke();
</script>
</body>
</html>

The fillText(): method draws filled text on the canvas. The default color of the text is black.
 Use the font property to specify font and font size.
 Use the fillStyle property to render the text in another color/gradient.

Syntax: context.fillText(text,x,y,maxWidth);
Where,
text - Specifies the text that will be written on the canvas
x - The x coordinate where to start painting the text (relative to the canvas)
y - The y coordinate where to start painting the text (relative to the canvas)
maxWidth - Optional. The maximum allowed width of the text, in pixels

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:10px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.font = "20px Georgia";


ctx.fillText("Hello World!", 10, 50);

ctx.font = "30px Verdana";


// Create gradient
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0"," magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");

// Fill with gradient


ctx.fillStyle = gradient;
ctx.fillText("Big smile!", 10, 90);
</script>
</body>
</html>
createLinearGradient(x,y,x1,y1) - creates a linear gradient
 Shapes on the canvas are not limited to solid colors. Gradients can be used to fill rectangles,
circles, lines, text, etc.
 Once we have a gradient object, we must add two or more color stops.
 The addColorStop() method specifies the color stops, and its position along the gradient.
Gradient positions can be anywhere between 0 to 1.
 To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape
(rectangle, text, or a line).

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:10px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0,200,200,0);
grd.addColorStop(0, "red");
grd.addColorStop(0.25, "white");
grd.addColorStop(0.5, "gray");
grd.addColorStop(1, "pink");

// Fill with gradient


ctx.fillStyle = grd;
ctx.fillRect(0, 0, 300,300);

</script>
</body>
</html>
Transformation of Shapes :
1) Scale:
The scale() method scales the current drawing, bigger or smaller. If you scale a drawing, all future
drawings will also be scaled. The positioning will also be scaled. If you scale(2,2); drawings will
be positioned twice as far from the left and top of the canvas as you specify.

Syntax: context.scale( scalewidth, scaleheight);


Where,
scalewidth - Scales the width of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
scaleheight - Scales the height of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)

<!DOCTYPE HTML>
<html>
<body>
<canvas id="mycanvas" style="border: 1px solid red;" width=380 height=350>
Canvas is not supported
</canvas>

<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");

ctx.strokeStyle= "Grey";
ctx.strokeRect(5, 5, 35, 25);

// Scale Rectangle 4 times bigger


ctx.scale(4, 4);
ctx.strokeStyle= "Yellow";
ctx.strokeRect(5, 5, 35, 25);

// Scale Rectangle to half


ctx.scale(0.5, 0.5);
ctx.strokeStyle= "Green";
ctx.strokeRect(5, 5,35, 25);

// Scale Rectangle 2 times bigger


ctx.scale(2, 2);
ctx.strokeStyle= "Red";
ctx.strokeRect(20, 20, 35, 25);
</script>
</body>
</html>
2. Translate:
The translate() method remaps the (0,0) position on the canvas.
When you call a method such as fillRect() after translate(), the value is added to the x- and y-
coordinate values.
Syntax: context.translate(x,y);
Where,
x - The value to add to horizontal (x) coordinates
y - The value to add to vertical (y) coordinates

<!DOCTYPE HTML>
<html>
<body>
<h2>Advanced Shapes</h2>
<canvas id="mycanvas" style="border: 1px solid red;" width=380 height=350>
Canvas is not supported
</canvas>

<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle="grey";
ctx.fillRect(10, 10, 100, 50);
ctx.translate(70, 70);
ctx.fillStyle="pink";
ctx.fillRect(10, 10, 100, 50);
</script>
</body>
</html>
3. Rotate:
The rotate() method rotates the current drawing.
The rotation will only affect drawings made AFTER the rotation is done.
Syntax: context.rotate(angle);
Where, angle - The rotation angle, in radians.
To calculate from degrees to radians: degrees*Math.PI/180.
Example: to rotate 5 degrees, specify the following: 5*Math.PI/180

<!DOCTYPE HTML>
<html>
<body>
<h2>Advanced Shapes</h2>
<canvas id="mycanvas" style="border: 1px solid red;" width=380 height=350>
Canvas is not supported
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");

ctx.strokeRect(100, 150, 150, 100);

//Rotate the rectangle 10 degrees:


ctx.rotate(10 * Math.PI / 180);
ctx.strokeRect(100, 150, 150, 100);

//Rotate the rectangle 30 degrees anticlockwise:


//Rotates with respect to previous rotation
ctx.rotate(-30 * Math.PI / 180);
ctx.strokeRect(100, 150, 150, 100);
</script>
</body>
</html>
Animation :
1. setInterval();
This method repeatedly executes the supplied code after a given timemilliseconds.
The setInterval() method, offered on the Window, repeatedly calls a function or executes a
code snippet, with a fixed time delay between each call.
This method returns an interval ID which uniquely identifies the interval, so you can remove
it later by calling clearInterval() .
Syntax: setInterval(callback, time);

2. clearInterval();
The global clearInterval() method cancels a timed, repeating action which was previously
established by a call to setInterval().
Syntax: clearInterval(intervalID);

3. setTimeout():
This method executes the supplied code only once after a given time milliseconds.
Syntax: setTimeout(callback, time);

4. requestAnimationFrame():
This method tells the browser that you wish to perform an animation and requests that the
browser calls a specified function to update an animation before the next repaint. The method
takes a callback as an argument to be invoked before the repaint.
Syntax: requestAnimationFrame(callback);
Rectangle Animation

<!DOCTYPE HTML>
<html>
<body>
<canvas id="mycanvas" style="border: 1px solid red;" width=380 height=350>
Canvas is not supported
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var startX = 10;
var startY = 10;
var width = height = 50;
var endX = canvas.width - width;
var x = startX;
var y = startY;
var step = 0;

function lerp(start, end, speed)


{
return start + (end - start) * speed;
}

function logic ()
{
step += 0.02;
x = lerp(startX, endX, step);
if (x < endX)
requestAnimationFrame(draw);
}

function draw()
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ff0000";
ctx.fillRect(x, y, width, height);
}
requestAnimationFrame(draw);
setInterval(logic, 1000/60);

</script>
</body>
</html>
Circle Animation

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width='300px' height='300px'/>
<script type='text/javascript'>
var canvas= document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var radius = 70;


var cx=cy=150;
ctx.lineWidth = 10;
ctx.strokeStyle="blue";
var angle = 0;
var newAngle=0;

function drawCircle()
{
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, newAngle * Math.PI);
ctx.stroke();
};

function go()
{
// Sincle Maximum angle is 2*PI, we use 2 for 200 divisions
if (angle < 200)
{
angle = angle + 1;
newAngle = angle *.01;
requestAnimationFrame(drawCircle);
}
}
requestAnimationFrame(drawCircle);
setInterval(go, 1000/60);
</script>
</body>
</html>
CanvasJS :
CanvasJS Charts is an HTML5 charting library that runs across devices and browsers to provide
businesses of any size with a tool to visualize their key data. CanvasJS Charts allows users to create
rich dashboards that work across devices without compromising on maintainability or functionality
of the web application.

Basic Column Chart_CanvasJS

<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script >
window.onload = function ()
{
var chart = new CanvasJS.Chart("chartContainer",
{
title:{text: "Top Oil Reserves"},
axisX:{title: "Countries"},
axisY:{title: "Reserves(MMbbl)"},
data: [{
type:"column", //bar, doughnut, line, pie
showInLegend:true,
legendText:"MMbbl = one million barrels",
dataPoints: [
{ y: 200878, label: "Venezuela" },
{ y: 196455, label: "Saudi" },
{ y: 179709, label: "Canada" },
{ y: 168400, label: "Iran" },
{ y: 155798, label: "Iraq" },
{ y: 164398, label: "UAE" }]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 100%; width: 100%;"></div>
</body>
</html>
Styling and Animation of Column Chart_CanvasJS
Enables Animation while rendering the Chart.
animationEnabled Options: true or false
animationDuration Sets the duration of animation in milliseconds.
Sets the theme of the Chart. Various predefined themes
theme are bundled along with the library.
Options: “light1″,”light2”, “dark1”, “dark2”
title
text Sets the Title’s text.
Sets the Font Family of Chart Title.
fontFamily
Example: “arial” , “tahoma”, “verdana”
fontColor Sets the font color of Chart Title.
fontSize Sets the font Size of Chart Title in pixels.
fontWeight Options: “lighter”, “normal”, “bold” , “bolder”
padding Allows you to set the padding for Chart Title.
margin Lets you set margin between Title & PlotArea.
Sets the maximum width of title after which it gets
maxWidth wrapped or clipped depending on whether wrap is set
to true (default) or false.
Wrap specifies whether to wrap the title once its width
wrap crosses maxWidth or not. If it is set to false, title gets
clipped after reaching maxWidth.
backgroundColor Sets the background color of Chart Title.
Sets the thickness of border around the Title in pixels.
borderThickness To display border around title, set the borderThickness
to a number greater than zero.
borderColor Sets the color of border around Chart Title.
To display rounded borders around the title, set the
cornerRadius cornerRadius of title. Higher the value, more rounded
are the corners.
Align the Chart Title vertically.
verticalAlign
Options: “top”, “center”, “bottom”
Align the Chart Title horizontally.
horizontalAlign
Options: “left”, “right”, “center”
axisX, axisY
title Sets the Axis Title.
Sets the Font Family of Axis Title.
titleFontFamily
Example: “calibri”, “tahoma, “verdana” ..
titleFontColor Sets the Font Color of Axis Title
titleFontSize Sets the Font Size of Axis Title in pixels.
Sets the Font Weight used in the Axis Title.
titleFontWeight
Options: “lighter”, “normal”, “bold” , “bolder”
labelFontFamily Sets the Font Family of Axis labels.
labelFontColor Sets the Axis Label color.
labelFontSize Sets the Axis Label Font Size in pixels.
Set the font Weight used in Axis Labels.
labelFontWeight
Options: “lighter”, “normal”, “bold” , “bolder”
Sets the text alignment of axis X or Y labels.
labelTextAlign
Options: “left”, “center”, “right”
labelPlacement allows you to position axisX label
labelPlacement either inside or outside the plot-area.
Options: “inside”, “outside”.
Sets the Dash Type for grid lines on axisX.
Options: “solid”, “shortDash”, “shortDot”,
gridDashType “shortDashDot”, “shortDashDotDot”, “dot”, “dash”
“dashDot”, “longDash”, “longDashDot”,
“longDashDotDot”
Sets the Thickness of Grid Lines. To display grid on
gridThickness Axis X, set the Grid Thickness to a number greater than
zero.
Sets the Interlacing Color that alternates between the
interlacedColor set interval. If the interval is not set explicitly, then the
auto calculated interval is considered.
gridColor Sets the Color of Grid Lines.
tickPlacement allows you to position axisX ticks either
tickPlacement inside or outside the plot-area.
Options: “inside”, “outside”.
Sets the length of Tick Marks that are drawn on the
tickLength
Axis.
tickColor Sets the color of Tick Marks drawn on the axis.
prefix A string that prepends all the labels on axis X or Y.
suffix A string that appends all the labels on axis X or Y.
Sets the distance between Tick Marks, Grid Lines and
Interlaced Colors.
interval
Default: Automatically Calculated
Example: 50, 75..
legend
Sets the cursor type for legend items.
cursor
Options: “pointer”, “crosshair” ..
Setting reversed property to true shows legend items in
reversed reverse order.
Options: true or false
Sets the maximum width of legend. If any item is
longer than the maxWidth, it gets wrapped or clipped
maxWidth
depending on the itemWrap property. itemWrap is true
by default.
Sets the maximum height of legend. Once the
maximum height is reached, remaining legend items
are not shown when horizontally stacked (while on top
maxHeight
or bottom or plotArea) and a new column is created
when items are vertically stacked (when displayed to
the left or right of plotArea).
itemWrap specifies whether to wrap or clip legendText
itemWrap
once its width crosses itemMaxWidth / maxWidth.
Sets the maximum width of individual legend items
after which they get wrapped or clipped depending on
itemMaxWidth whether itemWrap is set to true (default) or false.
itemMaxWidth can’t be greater than maxWidth of
legend.
Sets the mouseover event handler for the legend, which
itemmouseover is triggered when the user moves the mouse(input
device) over a legend item.
Align the Legend Position vertically.
verticalAlign
Options: “top”, “center”, “bottom”
Align the Legend Position horizontally.
horizontalAlign
Options: “left”, “right”, “center”

Example
<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script >
window.onload = function ()
{
var chart = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
animationDuration: 2000,
theme: "light1", // "light1", "light2", "dark1", "dark2"
title:{ text: "Olympic Medals",
fontFamily: "arial black",
fontColor: "Red",
fontSize: 30,
fontWeight: "bold",
padding: 10,
margin: 15,
maxWidth: 1000,
wrap:true,
backgroundColor: "Pink",
borderThickness: 5,
borderColor: "Red",
cornerRadius: 5,
verticalAlign:"bottom",
horizontalAlign:"center"
},

axisX:{ title: "Countries",


titleFontFamily: "verdana",
titleFontColor: "blue",
titleFontSize: 25,
titleFontWeight: "bold",
labelFontFamily: "tahoma",
labelFontSize: 10,
labelFontWeight: "bolder",
gridDashType: "dot",
gridThickness: 2,
interlacedColor: "#F8F1E4",
gridColor: "orange",
labelPlacement:"inside",
tickPlacement:"inside",
tickLength: 5,
tickColor: "red"
},

axisY:{ title: "Medals",


titleFontFamily: "verdana",
titleFontColor: "blue",
titleFontSize: 25,
titleFontWeight: "bold",
labelFontFamily: "tahoma",
labelFontSize: 10,
labelFontWeight: "bolder",
gridDashType: "dot",
gridThickness: 2,
interlacedColor: "#F8F1E4",
gridColor: "orange",
labelPlacement:"inside",
tickPlacement:"inside",
tickLength: 5,
tickColor: "red",
minimum: 200,
maximum: 610,
},
legend: {cursor: "crosshair",
reversed: true,
maxWidth: 200,
maxHeight: 200
itemWrap: false,
itemMaxWidth: 200,
itemmouseover: function(e){alert( "Mouse moved over the legend
item"); },
verticalAlign:"bottom",
horizontalAlign:"left"
},
data: [{
type: "column", //bar, doughnut, line, pie
showInLegend: true,
legendMarkerColor: "Green",
legendText: "Medal Counts",
dataPoints: [
{ y: 543, label: "India" },
{ y: 336, label: "China" },
{ y: 443, label: "France" },
{ y: 273, label: "Great Britain" },
{ y: 369, label: "Germany" },
{ y: 596, label: "Russia" },
{ y: 618, label: "USA" }]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 100%; width: 800px;"></div>
</body>
</html>
Multi Series Column Chart_CanvasJS
<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script >
window.onload = function ()
{
var chart = new CanvasJS.Chart("chartContainer",
{
title:{text: "Fruits sold in First & Second Quarter"},
axisX:{title: "Fruits"},
axisY:{ title: "Sale",
prefix: "$",
suffix: "K"},
data: [{
type: "column", //bar, line
showInLegend: true,
legendText: "First Quarter",
dataPoints: [
{ label: "Banana", y: 58 },
{ label: "Orange", y: 69 },
{ label: "Apple", y: 80 },
{ label: "Mango", y: 74 },
{ label: "Grape", y: 64 }]
},
{
type: "column", //bar, line
showInLegend: true,
legendText: "Second Quarter",
dataPoints: [
{ label: "Banana", y: 63 },
{ label: "Orange", y: 73 },
{ label: "Apple", y: 88 },
{ label: "Mango", y: 77 },
{ label: "Grape", y: 60 }]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 100%; width: 800px;"></div>
</body>
</html>
Stacked Column/Bar Chart_CanvasJS
<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script >
window.onload = function ()
{
var chart = new CanvasJS.Chart("chartContainer",
{
title:{text: "Fruits sold in First & Second Quarter"},
axisX:{title: "Fruits"},
axisY:{ title: "Sale",
prefix: "$",
suffix: "K"},
data: [{
type: "stackedColumn", //stackedBar
showInLegend: true,
legendText: "First Quarter",
dataPoints: [
{ label: "Banana", y: 58 },
{ label: "Orange", y: 69 },
{ label: "Apple", y: 80 },
{ label: "Mango", y: 74 },
{ label: "Grape", y: 64 }]
},
{
type: " stackedColumn ", // stackedBar
showInLegend: true,
legendText: "Second Quarter",
dataPoints: [
{ label: "Banana", y: 63 },
{ label: "Orange", y: 73 },
{ label: "Apple", y: 88 },
{ label: "Mango", y: 77 },
{ label: "Grape", y: 60 }]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 100%; width: 800px;"></div>
</body>
</html>
Basic Bar Chart_CanvasJS
<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js">
</script>
<script >
window.onload = function ()
{
var chart = new CanvasJS.Chart("chartContainer",
{
title:{text: "Quarterly Sales of Fruits"},

axisX:{ title: "Fruits",


prefix: "Q-",
suffix: "_2021"},

axisY:{ title: "Sale",


prefix: "$",
suffix: "K"},

legend:{ reversed: true, // shows legend items in reverse order.


verticalAlign:"top",
horizontalAlign:"center" },

data: [{
type:"bar", //column, doughnut, line, pie
showInLegend:true,
legendText:"Vegetables",
dataPoints: [
{ x: 1, y: 58},
{ x: 2, y: 69},
{ x: 3, y: 80},
{ x: 4, y: 74}]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 100%; width: 800px;"></div>
</body>
</html>
Basic Pie Chart_CanvasJS
<!DOCTYPE HTML>
<html>
<head>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script >
window.onload = function ()
{
var chart = new CanvasJS.Chart("chartContainer",
{
title:{text: "Olympic Medals"},

data: [{
type:"pie", //column, bar, doughnut, line
showInLegend:true,
indexLabel: "{name} {y}",

dataPoints: [
{ y: 543, name: "India", exploded: true},
{ y: 336, name: "China" },
{ y: 443, name: "France" },
{ y: 273, name: "Great Britain" },
{ y: 369, name: "Germany" },
{ y: 596, name: "Russia" },
{ y: 618, name: "USA" }]
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 100%; width: 800px;"></div>
</body>
</html>
Google API :

Basic Bar Chart_Google API


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['product', 'Sales'],
['Shoes', 40],
['Hats', 50],
['Coats', 35],
['Scarves', 20] ]);
var options = {title : "Product Sales",
hAxis: { title: "Sales" },
vAxis: { title: "Products" }};
var chart = new
google.visualization.BarChart(document.getElementById("chart"));
chart.draw(data,options);
}
</script>
</head>
<body>
<h1>Google API Bar Chart</h1>
<div id="chart" style="width:500px;height:100%;margin:0"></div>
</body>
</html>
Multi Series Bar Chart_Google API
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['product', 'Q1_Sales','Q2_Sales','Q3_Sales','Q4_Sales'],
['Shoes', 40, 50, 60, 55],
['Hats', 50, 55, 45, 60],
['Coats', 35, 40, 50, 45],
['Scarves', 40, 30, 35, 45] ]);
var options = { title : "Product Sales",
legend:"bottom",
hAxis: { title: "Sales" },
vAxis: { title: "Products"} };
var chart = new
google.visualization.BarChart(document.getElementById("chart"));
chart.draw(data,options);
}
</script>
</head>
<body>
<h1>Google API Bar Chart</h1>
<div id="chart" style="width:500px;height:100%;margin:0"></div>
</body>
</html>
Stacked Bar Chart_Google API
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['product', 'Q1_Sales','Q2_Sales','Q3_Sales','Q4_Sales'],
['Shoes', 40, 50, 60, 55],
['Hats', 50, 55, 45, 60],
['Coats', 35, 40, 50, 45],
['Scarves', 40, 30, 35, 45] ]);
var options = { title : "Product Sales",
isStacked: true,
legend:"bottom",
hAxis: { title: "Sales" },
vAxis: { title: "Products"} };
var chart = new
google.visualization.BarChart(document.getElementById("chart"));
chart.draw(data,options);
}
</script>
</head>
<body>
<h1>Google API Stacked Bar Chart</h1>
<div id="chart" style="width:500px;height:100%;margin:0"></div>
</body>
</html>
Styling BarChart_GoogleAPI
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['product', 'Sales', { role: 'annotation'}, { role: 'style'}],
['Shoes', 40, "40", 'color: gray'],
['Hats', 50, "50", 'opacity: 0.2'],
['Coats', 35, "35", 'stroke-color: pink; stroke-width: 4;
fill-color: #C5A5CF'],
['Scarves', 20, "20", 'stroke-color: blue; stroke-opacity: 0.6;
stroke-width: 8; fill-color: #BC5679; fill-opacity: 0.2']
]);
var options = { title : "Product Sales",
legend:"bottom",
hAxis: { title: "Sales" },
vAxis: { title: "Products" }};
var chart = new
google.visualization.BarChart(document.getElementById("chart"));
chart.draw(data,options);
}
</script>
</head>
<body>
<h1>Google API Bar Chart with Styling</h1>
<div id="chart" style="width:500px;height:100%;margin:0"></div>
</body>
</html>
Animating ColumnChart_GoogleAPI
<!DOCTYPE html>
<html>
<head>
<title>Google Charts API Column Chart Animated</title>

<script type="text/javascript" src="https://www.google.com/jsapi"></script>


<script type="text/javascript">
google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(renderChart);

function renderChart() {
var data = google.visualization.arrayToDataTable([
['product', 'Sales', { role: 'annotation' } ],
['Shoes', 40, "40"],
['Hats', 50, "50"],
['Coats', 35, "35"],
['Scarves', 20, "20"]
]);

var options = { title : "Product Sales",


vAxis:{ title: "Sales", viewWindow: { min: 0, max: 55 } },
hAxis:{ title: "Products" },
animation:{ startup:true,
duration: 1000,
easing: 'inAndOut'}
};

var chart = new


google.visualization.ColumnChart(document.getElementById("chart"));
chart.draw(data, options);

var button = document.getElementById('changeData');


var firstData = true;
button.onclick = function () {
if (!firstData) {
firstData = !firstData;
data.setValue(0, 1, 40);
data.setValue(1, 1, 50);
data.setValue(2, 1, 35);
data.setValue(3, 1, 20);

data.setValue(0, 2, "40");
data.setValue(1, 2, "50");
data.setValue(2, 2, "35");
data.setValue(3, 2, "20");
}
else{
firstData = !firstData;
data.setValue(0, 1, 25);
data.setValue(1, 1, 40);
data.setValue(2, 1, 45);
data.setValue(3, 1, 15);

data.setValue(0, 2, "25");
data.setValue(1, 2, "40");
data.setValue(2, 2, "45");
data.setValue(3, 2, "15");
}
chart.draw(data, options);
};
}
</script>
</head>
<body>
<h1>Google Column Chart Animated</h1>
<div id="chart" style='width: 550px; height: 40%'></div>
<div>
<input id="changeData" type="button" value="Change">
</div>
</body>
</html>
Basic Pie Chart_Google API
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['product', 'Sales'],
['Shoes', 40],
['Hats', 50],
['Coats', 35],
['Scarves', 20] ]);
var options = { title : "Product Sales",
pieHole: 0.4,
pieStartAngle: 90,
//is3D: true };
var chart = new
google.visualization.PieChart(document.getElementById("chart"));
chart.draw(data,options);
}
</script>
</head>
<body>
<h1>Google API Bar Chart</h1>
<div id="chart" style="width:500px;height:100%;margin:0"></div>
</body>
</html>
SVG:

You might also like