0% found this document useful (0 votes)
19 views90 pages

DV Lab Exp 1-3

The document provides a comprehensive guide on setting up environments for various data visualization tools, including Python-based libraries, Tableau, Power BI, R-based tools, and cloud-based options. It also includes multiple examples of developing graphical shapes using HTML5 Canvas and SVG, showcasing basic and advanced shapes with explanations for each. The document encourages customization and interactivity in the examples provided.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views90 pages

DV Lab Exp 1-3

The document provides a comprehensive guide on setting up environments for various data visualization tools, including Python-based libraries, Tableau, Power BI, R-based tools, and cloud-based options. It also includes multiple examples of developing graphical shapes using HTML5 Canvas and SVG, showcasing basic and advanced shapes with explanations for each. The document encourages customization and interactivity in the examples provided.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 90

Exp1:

1. Setup Environment for All the Tools

Setting up an environment for data visualization tools depends on the specific tools or frameworks you want to use.
Here’s a general guide to get you started:

1. Python-Based Tools (e.g., Matplotlib, Seaborn, Plotly, Dash)

 Install Python: Download and install Python from python.org.


 Set up a virtual environment:

bash

python -m venv myenv


source myenv/bin/activate # On Windows: myenv\Scripts\activate

 Install libraries:

bash

pip install matplotlib seaborn plotly dash

 Test your setup by creating a simple visualization:

python

import matplotlib.pyplot as plt


plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

2. Tableau

 Download Tableau Public or Tableau Desktop from tableau.com.


 Install the software and connect it to your data source (e.g., Excel, CSV, or database).
 Explore Tableau’s drag-and-drop interface to create visualizations.

3. Power BI

 Download Power BI Desktop from Microsoft.


 Install and connect it to your data source.
 Use the built-in tools to create dashboards and reports.

4. R-Based Tools (e.g., ggplot2, Shiny)

 Install R and RStudio from r-project.org and rstudio.com.


 Install libraries:

install.packages("ggplot2")
install.packages("shiny")
 Test your setup with a simple ggplot2 visualization:

library(ggplot2)
ggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point()

5. Cloud-Based Tools (e.g., Google Data Studio, Looker)

 For Google Data Studio, sign in with your Google account at datastudio.google.com.
 Connect to your data source and start building interactive dashboards.

If you have a specific tool in mind, let me know, and I can provide more tailored instructions!

Exp :2
2. Develop the following Program Using HTML5 CANVAS and SVG TAG
To develop a program using HTML5 Canvas and the SVG tag, here's an example code snippet that combines these
two features for creating and displaying shapes and animations:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>HTML5 Canvas and SVG Example</title>

<style>

svg {

display: block;

margin: 20px auto;

canvas {

display: block;

margin: 20px auto;

border: 1px solid black;

</style>
</head>

<body>

<h1>HTML5 Canvas and SVG Example</h1>

<!-- SVG Section -->

<svg width="200" height="200">

<circle cx="100" cy="100" r="50" fill="blue" />

<rect x="50" y="50" width="50" height="50" fill="red" />

<text x="10" y="190" font-size="18" fill="green">SVG Shapes</text>

</svg>

<!-- Canvas Section -->

<canvas id="canvas" width="200" height="200"></canvas>

<script>

// HTML5 Canvas Section

const canvas = document.getElementById('canvas');

const ctx = canvas.getContext('2d');

// Draw shapes on Canvas

ctx.fillStyle = 'blue';

ctx.beginPath();

ctx.arc(100, 100, 50, 0, Math.PI * 2);

ctx.fill();

ctx.fillStyle = 'red';

ctx.fillRect(75, 75, 50, 50);


ctx.fillStyle = 'green';

ctx.font = '18px Arial';

ctx.fillText('Canvas Shapes', 10, 190);

</script>

</body>

</html>

Explanation:

1. SVG Section:
o The <circle> element creates a blue circle.
o The <rect> element creates a red rectangle.
o The <text> element displays the text "SVG Shapes" in green color.
2. Canvas Section:
o The <canvas> tag provides a drawable area.
o The JavaScript code uses the getContext() method to draw a blue circle, a red rectangle, and
green text.

Feel free to adapt this code to your specific requirements or add interactivity! If you need further assistance with
enhancements or explanations, let me know!

2a. Develop the Different basic Graphical Shapes using HTM5 CANVAS
Here’s an example of how you can create different basic graphical shapes using HTML5 Canvas. The <canvas>
element, along with JavaScript, allows us to draw and manipulate shapes dynamically:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>HTML5 Canvas Basic Shapes</title>

<style>

canvas {

border: 1px solid black;

display: block;
margin: 20px auto;

</style>

</head>

<body>

<h1>HTML5 Canvas Basic Shapes</h1>

<canvas id="canvas" width="400" height="400"></canvas>

<script>

// Get the canvas element and context

const canvas = document.getElementById('canvas');

const ctx = canvas.getContext('2d');

// Draw a rectangle

ctx.fillStyle = 'blue';

ctx.fillRect(50, 50, 100, 50);

// Draw a circle

ctx.fillStyle = 'red';

ctx.beginPath();

ctx.arc(200, 100, 50, 0, Math.PI * 2); // x, y, radius, startAngle, endAngle

ctx.fill();

// Draw a line

ctx.strokeStyle = 'green';

ctx.lineWidth = 5;

ctx.beginPath();

ctx.moveTo(50, 200); // Starting point


ctx.lineTo(250, 200); // Ending point

ctx.stroke();

// Draw a triangle

ctx.fillStyle = 'orange';

ctx.beginPath();

ctx.moveTo(300, 300); // Starting point

ctx.lineTo(350, 350); // Second point

ctx.lineTo(250, 350); // Third point

ctx.closePath(); // Closes the triangle

ctx.fill();

// Draw an ellipse

ctx.fillStyle = 'purple';

ctx.beginPath();

ctx.ellipse(100, 300, 50, 25, 0, 0, Math.PI * 2); // x, y, radiusX, radiusY, rotation, startAngle, endAngle

ctx.fill();

</script>

</body>

</html>

Explanation of the Code:

1. Rectangle:
o ctx.fillRect(x, y, width, height) draws a solid rectangle.
2. Circle:
o ctx.arc(x, y, radius, startAngle, endAngle) creates a circular path, and
ctx.fill() fills it with color.
3. Line:
o Use ctx.beginPath(), ctx.moveTo(), and ctx.lineTo() to draw a line, and
ctx.stroke() to render it.
4. Triangle:
o Move to the first point, then draw lines to the next two points using ctx.lineTo(). Finally,
close the path with ctx.closePath() and fill it.
5. Ellipse:
o ctx.ellipse() creates an ellipse with specified radii and orientation.

This script sets up a canvas and demonstrates how to draw five basic shapes: rectangle, circle, line, triangle, and
ellipse. You can modify the colors, positions, and sizes to suit your needs! If you'd like more examples or advanced
shapes, just let me know.

2b. Develop the Different Advanced Graphical Shapes using HTM5 CANVAS
Developing advanced graphical shapes with HTML5 Canvas involves combining geometric primitives,
transformations, patterns, and effects to create more intricate visuals. Here's an example of some advanced
shapes and techniques:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>HTML5 Canvas Advanced Shapes</title>

<style>

canvas {

border: 1px solid black;

display: block;

margin: 20px auto;

</style>

</head>

<body>

<h1>HTML5 Canvas Advanced Shapes</h1>

<canvas id="canvas" width="500" height="500"></canvas>

<script>

const canvas = document.getElementById('canvas');

const ctx = canvas.getContext('2d');


// Advanced Shape 1: Gradient Circle

const gradient = ctx.createRadialGradient(250, 250, 50, 250, 250, 150);

gradient.addColorStop(0, 'blue');

gradient.addColorStop(1, 'white');

ctx.fillStyle = gradient;

ctx.beginPath();

ctx.arc(250, 250, 150, 0, Math.PI * 2);

ctx.fill();

// Advanced Shape 2: Star

function drawStar(ctx, x, y, radius, points, inset) {

ctx.beginPath();

const step = Math.PI / points;

for (let i = 0; i < Math.PI * 2; i += step) {

const outerX = x + Math.cos(i) * radius;

const outerY = y + Math.sin(i) * radius;

ctx.lineTo(outerX, outerY);

const innerX = x + Math.cos(i + step / 2) * radius * inset;

const innerY = y + Math.sin(i + step / 2) * radius * inset;

ctx.lineTo(innerX, innerY);

ctx.closePath();

ctx.fillStyle = 'gold';

ctx.fill();

}
drawStar(ctx, 150, 150, 50, 5, 0.5);

// Advanced Shape 3: Pattern-Filled Rectangle

const img = new Image();

img.src = 'https://via.placeholder.com/100';

img.onload = () => {

const pattern = ctx.createPattern(img, 'repeat');

ctx.fillStyle = pattern;

ctx.fillRect(50, 300, 200, 100);

};

// Advanced Shape 4: Bezier Curve

ctx.strokeStyle = 'purple';

ctx.lineWidth = 3;

ctx.beginPath();

ctx.moveTo(300, 400);

ctx.bezierCurveTo(350, 300, 450, 300, 400, 400);

ctx.stroke();

// Advanced Shape 5: Polygon

function drawPolygon(ctx, x, y, radius, sides) {

ctx.beginPath();

for (let i = 0; i < sides; i++) {

const angle = (i * 2 * Math.PI) / sides;

const polygonX = x + radius * Math.cos(angle);

const polygonY = y + radius * Math.sin(angle);

ctx.lineTo(polygonX, polygonY);
}

ctx.closePath();

ctx.fillStyle = 'cyan';

ctx.fill();

drawPolygon(ctx, 400, 150, 60, 6);

</script>

</body>

</html>

Features of This Code:

1. Gradient Circle:
o Uses a radial gradient to create a shaded circle for a 3D effect.
2. Star Shape:
o A function draws a custom star with adjustable points and inset values for spikes.
3. Pattern-Filled Rectangle:
o Uses createPattern() to fill a rectangle with a tiled image pattern.
4. Bezier Curve:
o Demonstrates a smooth and elegant curve controlled by Bezier control points.
5. Polygon:
o A dynamic function creates a polygon with customizable sides and size.

How It Works:

 Run this HTML file in a browser, and you'll see all these advanced shapes rendered on the Canvas.
 Feel free to adjust colors, sizes, and positions, or add animation for even more interactivity. Let me know if
you'd like help making these shapes dynamic!

2c. Develop the Different basic Graphical Shapes using HTM5 SVG

Here’s an example of how to create different basic graphical shapes using the HTML5 <svg> tag. SVG (Scalable
Vector Graphics) is perfect for drawing vector-based shapes directly in HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG Basic Shapes</title>
<style>
svg {
display: block;
margin: 20px auto;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>SVG Basic Shapes</h1>
<svg width="400" height="400">
<!-- Rectangle -->
<rect x="50" y="50" width="100" height="50" fill="blue" />

<!-- Circle -->


<circle cx="200" cy="100" r="50" fill="red" />

<!-- Ellipse -->


<ellipse cx="100" cy="200" rx="60" ry="30" fill="purple" />

<!-- Line -->


<line x1="50" y1="250" x2="250" y2="350" stroke="green" stroke-width="5" />

<!-- Polygon (Triangle) -->


<polygon points="300,300 350,350 250,350" fill="orange" />

<!-- Polyline -->


<polyline points="50,300 70,330 90,300 110,330 130,300" stroke="black" stroke-width="2"
fill="none" />

<!-- Text -->


<text x="150" y="370" font-size="20" fill="brown">SVG Shapes</text>
</svg>
</body>
</html>

Explanation of Each Shape:

1. Rectangle:
o <rect> defines a rectangle with x and y as the top-left corner coordinates, and width and
height for size.
2. Circle:
o <circle> defines a circle using cx (center x), cy (center y), and r (radius).
3. Ellipse:
o <ellipse> creates an oval shape, defined by cx, cy, rx (horizontal radius), and ry (vertical
radius).
4. Line:
o <line> connects two points, defined by x1, y1 (starting point) and x2, y2 (ending point).
5. Polygon:
o <polygon> draws a closed shape with vertices specified in the points attribute.
6. Polyline:
o <polyline> is similar to a polygon but does not close the shape automatically.
7. Text:
o <text> is used to display text at specific coordinates, with customizable styles.

How It Works:

 Copy and paste the code into an HTML file and open it in a browser to see the various shapes rendered on
the page.
 SVG is scalable and resolution-independent, making it great for creating high-quality graphics.

2d. Develop the Different Advanced Graphical Shapes using HTM5 SVG

Here’s an example of how to create advanced graphical shapes using HTML5 SVG. SVG provides a wide variety of
features to create intricate and dynamic shapes, including gradients, patterns, paths, and transformations. Here's
how you can implement some advanced examples:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>SVG Advanced Shapes</title>

<style>

svg {

display: block;

margin: 20px auto;

border: 1px solid black;

</style>

</head>

<body>

<h1>SVG Advanced Shapes</h1>

<svg width="500" height="500">

<!-- Gradient-Filled Circle -->

<defs>

<radialGradient id="gradient1" cx="50%" cy="50%" r="50%">

<stop offset="0%" stop-color="blue" />

<stop offset="100%" stop-color="white" />

</radialGradient>
</defs>

<circle cx="150" cy="150" r="100" fill="url(#gradient1)" />

<!-- Complex Path (Heart Shape) -->

<path d="M250 300

C 200 200, 100 200, 150 350

C 200 500, 300 500, 350 350

C 400 200, 300 200, 250 300"

fill="red" />

<!-- Pattern-Filled Rectangle -->

<defs>

<pattern id="pattern1" width="10" height="10" patternUnits="userSpaceOnUse">

<circle cx="5" cy="5" r="3" fill="green" />

</pattern>

</defs>

<rect x="50" y="400" width="200" height="100" fill="url(#pattern1)" />

<!-- Star (Polygon) -->

<polygon points="400,150 420,200 470,200 430,240 450,300

400,260 350,300 370,240 330,200 380,200"

fill="gold" />

<!-- Cubic Bézier Curve -->

<path d="M50 450 C150 350, 350 550, 450 450"

stroke="purple" stroke-width="4" fill="none" />

</svg>
</body>

</html>

Features of This Code:

1. Gradient-Filled Circle:
o Uses <radialGradient> to fill the circle with a smooth gradient transitioning from blue to
white.
2. Complex Path (Heart Shape):
o The <path> element uses cubic Bézier curves (C) to create a heart shape.
3. Pattern-Filled Rectangle:
o A <pattern> is defined with small green circles, and the rectangle is filled with this repeating
pattern.
4. Star:
o A custom polygon with multiple points is used to create a star shape.
5. Cubic Bézier Curve:
o A curved path is drawn using control points for smooth transitions, styled with a purple stroke.

How to Use:

 Copy and paste the code into an HTML file and open it in your browser to view the advanced SVG shapes.
 You can customize the colors, positions, and sizes of shapes to fit your needs.

Let me know if you'd like more animations, interactivity, or additional SVG features! These advanced shapes can be
combined with CSS or JavaScript to create even more dynamic

Exp:3
Develop Following Program Using HTML5 and
HTML5 and data visualization, here's an example that combines HTML5 with JavaScript and a popular data
visualization library, such as Chart.js, to create an interactive bar chart:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>HTML5 Data Visualization Example</title>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <!-- Include Chart.js library -->

</head>

<body>

<h1>Data Visualization Using HTML5</h1>

<canvas id="myChart" width="400" height="200"></canvas> <!-- Canvas for Chart.js -->


<script>

// Example data

const labels = ['January', 'February', 'March', 'April', 'May'];

const data = {

labels: labels,

datasets: [{

label: 'Monthly Sales (in USD)',

data: [5000, 7000, 8000, 6000, 9000],

backgroundColor: 'rgba(75, 192, 192, 0.2)',

borderColor: 'rgba(75, 192, 192, 1)',

borderWidth: 1

}]

};

// Chart configuration

const config = {

type: 'bar', // Type of chart: bar, line, pie, etc.

data: data,

options: {

scales: {

y: {

beginAtZero: true

};
// Render the chart

const myChart = new Chart(

document.getElementById('myChart'),

config

);

</script>

</body>

</html>

Key Points:

1. HTML5 Canvas:
o The <canvas> element serves as the container for the data visualization. It is rendered using the
Chart.js library.
2. Chart.js Library:
o The example uses Chart.js to generate a responsive bar chart. You can include Chart.js via a CDN
as shown in the <script> tag.
3. Data and Configuration:
o The data object specifies the labels (categories) and datasets (values) for the chart.
o The config object defines the chart type (bar chart in this case) and its display options.
4. Customizing the Chart:
o Modify the labels and data.datasets.data arrays to display your specific data.
o Change the type in the config object to switch to other chart types like line, pie, or
doughnut.

How to Run:

1. Copy the code into an .html file and open it in a web browser.
2. You’ll see a bar chart that displays the sales data for each month.

Would you like further enhancements, such as adding multiple datasets, interactivity (e.g., tooltips), or switching to
a different type of chart? Just let me know!

3a. Develop the simple bar chart usingHTML5 CANVAS

Here’s how you can develop a simple bar chart using HTML5 Canvas. This example demonstrates how to use the
<canvas> element and JavaScript to draw a basic bar chart:

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Simple Bar Chart</title>

<style>

canvas {

display: block;

margin: 20px auto;

border: 1px solid black;

</style>

</head>

<body>

<h1>Simple Bar Chart Using HTML5 Canvas</h1>

<canvas id="barChart" width="500" height="400"></canvas>

<script>

// Data for the bar chart

const data = [30, 70, 50, 90, 110]; // Heights of the bars

const labels = ['A', 'B', 'C', 'D', 'E']; // Labels for each bar

const barWidth = 50; // Width of each bar

const barSpacing = 20; // Spacing between bars

const canvas = document.getElementById('barChart');

const ctx = canvas.getContext('2d');

// Chart setup

const canvasWidth = canvas.width;

const canvasHeight = canvas.height;


const maxDataValue = Math.max(...data);

const scaleFactor = (canvasHeight - 50) / maxDataValue; // Scale data to fit in canvas

// Draw bars

data.forEach((value, index) => {

const barHeight = value * scaleFactor;

const x = 50 + index * (barWidth + barSpacing); // Calculate x position of the bar

const y = canvasHeight - barHeight - 30; // y position based on the height

// Draw bar

ctx.fillStyle = 'blue';

ctx.fillRect(x, y, barWidth, barHeight);

// Draw label below the bar

ctx.fillStyle = 'black';

ctx.font = '14px Arial';

ctx.textAlign = 'center';

ctx.fillText(labels[index], x + barWidth / 2, canvasHeight - 10);

});

// Draw axes

ctx.strokeStyle = 'black';

ctx.lineWidth = 2;

ctx.beginPath();

ctx.moveTo(40, 10); // y-axis

ctx.lineTo(40, canvasHeight - 30);

ctx.lineTo(canvasWidth - 10, canvasHeight - 30); // x-axis


ctx.stroke();

// Add title

ctx.fillStyle = 'black';

ctx.font = '16px Arial';

ctx.textAlign = 'center';

ctx.fillText('Simple Bar Chart', canvasWidth / 2, 30);

</script>

</body>

</html>

Explanation:

1. Canvas Setup:
o A <canvas> element is used as a container for the bar chart, and a 2D rendering context
(getContext('2d')) is used to draw shapes.
2. Data and Labels:
o The data array contains the values for the height of each bar, while the labels array provides
labels for each bar.
3. Dynamic Bar Drawing:
o Each bar is scaled according to the maximum data value and the canvas height.
4. Axes and Labels:
o Basic x and y axes are drawn for reference, and labels are placed under each bar.
5. Title:
o The chart has a title displayed at the top.

How to Run:

1. Copy and save the code as an .html file.


2. Open the file in a browser.
3. You’ll see a simple bar chart with labeled bars and axes.

Let me know if you'd like enhancements, such as grid lines, legends, or animations!

3b. Read the data .txt file and draw Data Table

To visualize data from a .txt file and display it in a data table using HTML5, JavaScript, and a bit of CSS, here's
an example implementation:

Steps:
1. Use a .txt file with tabular data, where rows and columns are separated by a specific delimiter (e.g.,
commas or tabs).
2. Use JavaScript to read and parse the data from the file.

Name,Age,Occupation

Alice,30,Engineer

Bob,25,Designer

Charlie,35,Teacher

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Data Table Visualization</title>

<style>

table {

border-collapse: collapse;

width: 80%;

margin: 20px auto;

table, th, td {

border: 1px solid black;

th, td {

padding: 10px;

text-align: center;

th {

background-color: #f2f2f2;
}

</style>

</head>

<body>

<h1>Data Table Visualization</h1>

<input type="file" id="fileInput" />

<div id="tableContainer"></div>

<script>

const fileInput = document.getElementById('fileInput');

const tableContainer = document.getElementById('tableContainer');

// Function to generate table from parsed data

function generateTable(data) {

const table = document.createElement('table');

const rows = data.split('\n');

rows.forEach((row, rowIndex) => {

const tr = document.createElement('tr');

const cells = row.split(',');

cells.forEach(cell => {

const cellElement = rowIndex === 0 ? document.createElement('th') : document.createElement('td');

cellElement.textContent = cell.trim();

tr.appendChild(cellElement);

});
table.appendChild(tr);

});

tableContainer.innerHTML = ''; // Clear previous table (if any)

tableContainer.appendChild(table);

// Event listener for file input

fileInput.addEventListener('change', (event) => {

const file = event.target.files[0];

if (file) {

const reader = new FileReader();

reader.onload = () => {

generateTable(reader.result); // Read and parse the file

};

reader.readAsText(file);

});

</script>

</body>

</html>

ow It Works:

1. User File Input:


o The <input type="file"> element allows the user to upload a .txt file.
2. JavaScript FileReader:
o The FileReader object reads the contents of the file as text.
3. Table Generation:
o The data is split into rows and columns using .split('\n') for rows and .split(',') for
columns.
o A <table> is dynamically created with <th> (header) and <td> (data) elements.
4. Styling:
o CSS is used to format the table for better visualization.

How to Use:

1. Copy and save the HTML file.


2. Save the sample data.txt file and ensure the delimiter matches the one in the script.
3. Open the HTML file in a browser, upload the .txt file via the input, and view the rendered table.
4.
3c. Read the data .txt file and draw Simple Bar Chart
To read data from a file and use it to draw a simple bar chart, we can use
JavaScript to load and parse the file. Here's an example of how you can achieve
this

<!DOCTYPE html>

<html>

<head>

<title>Simple Bar Chart from File</title>

</head>

<body>

<input type="file" id="fileInput" />

<canvas id="barChart" width="600" height="400" style="border:1px solid


#000;"></canvas>

<script>

const canvas = document.getElementById('barChart');

const ctx = canvas.getContext('2d');

document.getElementById('fileInput').addEventListener('change',
function(event) {
const file = event.target.files[0];

if (file) {

const reader = new FileReader();

// Read the file content

reader.onload = function(e) {

const text = e.target.result;

// Process the file content (assuming it's in the format "label,value"


per line)

const lines = text.split('\n');

const labels = [];

const data = [];

lines.forEach(line => {

const [label, value] = line.split(',');

if (label && value) {

labels.push(label.trim());

data.push(Number(value.trim()));

});
drawBarChart(labels, data);

};

reader.readAsText(file);

});

function drawBarChart(labels, data) {

ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas

const barWidth = 50;

const barSpacing = 20;

const chartHeight = canvas.height - 50;

// Draw the bars

data.forEach((value, index) => {

const barHeight = (value / Math.max(...data)) * chartHeight; // Scale


the bars

const x = 50 + index * (barWidth + barSpacing);

const y = canvas.height - barHeight;


// Draw the bar

ctx.fillStyle = "skyblue";

ctx.fillRect(x, y, barWidth, barHeight);

// Draw the label

ctx.fillStyle = "black";

ctx.textAlign = "center";

ctx.fillText(labels[index], x + barWidth / 2, canvas.height - 10);

});

// Draw the chart axis

ctx.beginPath();

ctx.moveTo(50, canvas.height - 50);

ctx.lineTo(50, 10);

ctx.moveTo(50, canvas.height - 50);

ctx.lineTo(canvas.width - 10, canvas.height - 50);

ctx.stroke();

</script>

</body>

</html>

How to Use
This way, you can dynamically visualize data from a file. Let me know if you
need help with something specific!

3d. Read the data .csv file and draw Data Table
You can use an HTML element and JavaScript to read data from a file and
dynamically create a data table. Here's an example:

<!DOCTYPE html>

<html>

<head>

<title>Data Table from CSV</title>

<style>

table {

width: 80%;

border-collapse: collapse;

margin: 20px auto;

th, td {

border: 1px solid #000;

padding: 8px;

text-align: center;

th {
background-color: #f2f2f2;

</style>

</head>

<body>

<input type="file" id="fileInput" accept=".csv" />

<div id="tableContainer"></div>

<script>

document.getElementById('fileInput').addEventListener('change',
function(event) {

const file = event.target.files[0];

if (file) {

const reader = new FileReader();

// Read the file content

reader.onload = function(e) {

const text = e.target.result;

// Parse CSV data

const rows = text.split('\n');


const table = document.createElement('table');

rows.forEach((row, rowIndex) => {

const cells = row.split(',');

const tr = document.createElement('tr');

cells.forEach(cell => {

const cellElement = rowIndex === 0 ?


document.createElement('th') : document.createElement('td');

cellElement.textContent = cell.trim();

tr.appendChild(cellElement);

});

table.appendChild(tr);

});

// Display the table

const container = document.getElementById('tableContainer');

container.innerHTML = ''; // Clear previous table

container.appendChild(table);

};

reader.readAsText(file);
}

});

</script>

</body>

</html>

How to Use:

Let me know if you'd like me to help tweak or expand this functionality!

3e. Read the data .csv file and draw Column Bar Chart
Here’s an example of how you can read data from a file and dynamically draw a
column bar chart using the HTML5 element and JavaScript:

<!DOCTYPE html>

<html>

<head>

<title>Column Bar Chart from CSV</title>

</head>

<body>

<input type="file" id="fileInput" accept=".csv" />

<canvas id="barChart" width="800" height="500" style="border:1px solid


#000;"></canvas>

<script>
const canvas = document.getElementById('barChart');

const ctx = canvas.getContext('2d');

document.getElementById('fileInput').addEventListener('change',
function(event) {

const file = event.target.files[0];

if (file) {

const reader = new FileReader();

// Read the file content

reader.onload = function(e) {

const text = e.target.result;

// Process the CSV data

const rows = text.split('\n');

const labels = [];

const data = [];

rows.forEach((row, index) => {

const cells = row.split(',');

if (index === 0) return; // Skip the header


if (cells[0] && cells[1]) {

labels.push(cells[0].trim());

data.push(Number(cells[1].trim()));

});

drawColumnBarChart(labels, data);

};

reader.readAsText(file);

});

function drawColumnBarChart(labels, data) {

ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas

const chartHeight = canvas.height - 50;

const barWidth = 50;

const barSpacing = 30;

// Draw the bars

data.forEach((value, index) => {


const barHeight = (value / Math.max(...data)) * chartHeight; // Scale
the bars

const x = 50 + index * (barWidth + barSpacing);

const y = canvas.height - barHeight;

// Draw the bar

ctx.fillStyle = "steelblue";

ctx.fillRect(x, y, barWidth, barHeight);

// Draw the label below the bar

ctx.fillStyle = "black";

ctx.textAlign = "center";

ctx.fillText(labels[index], x + barWidth / 2, canvas.height - 10);

});

// Draw the chart axis

ctx.beginPath();

ctx.moveTo(50, canvas.height - 50);

ctx.lineTo(50, 10);

ctx.moveTo(50, canvas.height - 50);

ctx.lineTo(canvas.width - 10, canvas.height - 50);

ctx.stroke();
}

</script>

</body>

</html>

Output:

Label,Value

January,10

February,15

March,20

April,25

May,30

3f. Read the data XML file and draw Data Table

<!DOCTYPE html>

<html>

<head>

<title>Data Table from XML</title>

<style>

table {

width: 80%;

border-collapse: collapse;

margin: 20px auto;


}

th, td {

border: 1px solid #000;

padding: 8px;

text-align: center;

th {

background-color: #f2f2f2;

</style>

</head>

<body>

<input type="file" id="fileInput" accept=".xml" />

<div id="tableContainer"></div>

<script>

document.getElementById('fileInput').addEventListener('change',
function(event) {

const file = event.target.files[0];

if (file) {

const reader = new FileReader();


// Read the file content

reader.onload = function(e) {

const text = e.target.result;

// Parse the XML data

const parser = new DOMParser();

const xmlDoc = parser.parseFromString(text, "text/xml");

// Extract data (assuming the XML structure is known)

const rows = xmlDoc.getElementsByTagName('row');

const table = document.createElement('table');

const headerRow = document.createElement('tr');

// Create table headers

const columns = rows[0]?.children;

if (columns) {

for (let i = 0; i < columns.length; i++) {

const th = document.createElement('th');

th.textContent = columns[i].nodeName;

headerRow.appendChild(th);

}
table.appendChild(headerRow);

// Populate table rows

for (let i = 0; i < rows.length; i++) {

const tr = document.createElement('tr');

for (let j = 0; j < rows[i].children.length; j++) {

const td = document.createElement('td');

td.textContent = rows[i].children[j].textContent;

tr.appendChild(td);

table.appendChild(tr);

// Display the table

const container = document.getElementById('tableContainer');

container.innerHTML = ''; // Clear previous table

container.appendChild(table);

};

reader.readAsText(file);

}
});

</script>

</body>

</html>

<data>

<row>

<Name>John</Name>

<Age>30</Age>

<City>New York</City>

</row>

<row>

<Name>Jane</Name>

<Age>25</Age>

<City>Los Angeles</City>

</row>

<row>

<Name>Mike</Name>

<Age>35</Age>

<City>Chicago</City>

</row>

</data>
3g. Read the data XML file and draw Simple Chart
<!DOCTYPE html>
<html>
<head>
<title>Simple Chart from XML</title>
</head>
<body>
<input type="file" id="fileInput" accept=".xml" />
<canvas id="chartCanvas" width="800" height="500" style="border:1px
solid #000;"></canvas>

<script>
const canvas = document.getElementById('chartCanvas');
const ctx = canvas.getContext('2d');

document.getElementById('fileInput').addEventListener('change',
function(event) {
const file = event.target.files[0];

if (file) {
const reader = new FileReader();

// Read the XML file content


reader.onload = function(e) {
const text = e.target.result;

// Parse XML
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(text, "text/xml");

// Extract data from the XML (assuming a specific structure)


const items = xmlDoc.getElementsByTagName("item");
const labels = [];
const data = [];

for (let i = 0; i < items.length; i++) {


const label = items[i].getElementsByTagName("label")
[0]?.textContent.trim();
const value = items[i].getElementsByTagName("value")
[0]?.textContent.trim();
if (label && value) {
labels.push(label);
data.push(Number(value));
}
}

drawSimpleChart(labels, data);
};

reader.readAsText(file);
}
});

function drawSimpleChart(labels, data) {


ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas

const chartHeight = canvas.height - 50;


const barWidth = 50;
const barSpacing = 30;

// Draw bars for the chart


data.forEach((value, index) => {
const barHeight = (value / Math.max(...data)) * chartHeight; // Scale
bars
const x = 50 + index * (barWidth + barSpacing);
const y = canvas.height - barHeight;

// Draw the bar


ctx.fillStyle = "steelblue";
ctx.fillRect(x, y, barWidth, barHeight);

// Draw the label


ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.fillText(labels[index], x + barWidth / 2, canvas.height - 10);
});

// Draw the axes


ctx.beginPath();
ctx.moveTo(50, canvas.height - 50);
ctx.lineTo(50, 10);
ctx.moveTo(50, canvas.height - 50);
ctx.lineTo(canvas.width - 10, canvas.height - 50);
ctx.stroke();
}
</script>
</body>
</html>
<data>
<item>
<label>January</label>
<value>10</value>
</item>
<item>
<label>February</label>
<value>15</value>
</item>
<item>
<label>March</label>
<value>20</value>
</item>
<item>
<label>April</label>
<value>25</value>
</item>
</data>

3h. Read JSON Data and draw Data Table

Here's an example of how to read JSON data and dynamically create a data
table in HTML using JavaScript:

<!DOCTYPE html>

<html>

<head>

<title>Data Table from JSON</title>


<style>

table {

width: 80%;

border-collapse: collapse;

margin: 20px auto;

th, td {

border: 1px solid #000;

padding: 8px;

text-align: center;

th {

background-color: #f2f2f2;

</style>

</head>

<body>

<input type="file" id="fileInput" accept=".json" />

<div id="tableContainer"></div>

<script>
document.getElementById('fileInput').addEventListener('change',
function(event) {

const file = event.target.files[0];

if (file) {

const reader = new FileReader();

// Read the JSON file content

reader.onload = function(e) {

const text = e.target.result;

const jsonData = JSON.parse(text); // Parse the JSON data

// Create table dynamically

createTable(jsonData);

};

reader.readAsText(file);

});

function createTable(data) {

const table = document.createElement('table');


const headerRow = document.createElement('tr');

// Generate table headers dynamically

const headers = Object.keys(data[0]);

headers.forEach(header => {

const th = document.createElement('th');

th.textContent = header;

headerRow.appendChild(th);

});

table.appendChild(headerRow);

// Populate table rows

data.forEach(row => {

const tr = document.createElement('tr');

headers.forEach(header => {

const td = document.createElement('td');

td.textContent = row[header];

tr.appendChild(td);

});

table.appendChild(tr);

});
// Display the table

const container = document.getElementById('tableContainer');

container.innerHTML = ''; // Clear previous table

container.appendChild(table);

</script>

</body>

</html>

{"Name": "John", "Age": 30, "City": "New York"},

{"Name": "Jane", "Age": 25, "City": "Los Angeles"},

{"Name": "Mike", "Age": 35, "City": "Chicago"}

3i. Read JSON Data and draw Simple Chart


Here's an example of how to read data from a JSON file and draw a simple chart
(like a bar chart) using the element and JavaScript:

<!DOCTYPE html>

<html>

<head>

<title>Simple Chart from JSON</title>

</head>

<body>

<input type="file" id="fileInput" accept=".json" />


<canvas id="chartCanvas" width="800" height="500" style="border:1px solid
#000;"></canvas>

<script>

const canvas = document.getElementById('chartCanvas');

const ctx = canvas.getContext('2d');

document.getElementById('fileInput').addEventListener('change',
function(event) {

const file = event.target.files[0];

if (file) {

const reader = new FileReader();

// Read the JSON file

reader.onload = function(e) {

const jsonData = JSON.parse(e.target.result);

// Extract labels and data (assuming JSON structure is an array of


objects)

const labels = [];

const data = [];


jsonData.forEach(item => {

labels.push(item.label);

data.push(item.value);

});

drawSimpleChart(labels, data);

};

reader.readAsText(file);

});

function drawSimpleChart(labels, data) {

ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas

const chartHeight = canvas.height - 50;

const barWidth = 50;

const barSpacing = 30;

// Draw bars for the chart

data.forEach((value, index) => {


const barHeight = (value / Math.max(...data)) * chartHeight; // Scale
bars

const x = 50 + index * (barWidth + barSpacing);

const y = canvas.height - barHeight;

// Draw the bar

ctx.fillStyle = "steelblue";

ctx.fillRect(x, y, barWidth, barHeight);

// Draw the label

ctx.fillStyle = "black";

ctx.textAlign = "center";

ctx.fillText(labels[index], x + barWidth / 2, canvas.height - 10);

});

// Draw the axes

ctx.beginPath();

ctx.moveTo(50, canvas.height - 50);

ctx.lineTo(50, 10);

ctx.moveTo(50, canvas.height - 50);

ctx.lineTo(canvas.width - 10, canvas.height - 50);

ctx.stroke();
}

</script>

</body>

</html>

[output:

{"label": "January", "value": 10},

{"label": "February", "value": 15},

{"label": "March", "value": 20},

{"label": "April", "value": 25},

{"label": "May", "value": 30}


exp4. Develop Following Program Using HTML5 and D3.js and Canvas.js
To create a simple column chart using HTML5, D3.js, and optionally Canvas.js,
here's an example using D3.js for dynamic and interactive visualization:

<!DOCTYPE html>

<html>

<head>

<title>Simple Column Chart with D3.js</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="800" height="500"></svg>

<script>
// Sample data

const data = [

{ label: "January", value: 10 },

{ label: "February", value: 20 },

{ label: "March", value: 15 },

{ label: "April", value: 25 },

{ label: "May", value: 30 }

];

// Set chart dimensions

const svgWidth = 800, svgHeight = 500;

const margin = { top: 20, right: 30, bottom: 50, left: 50 };

const width = svgWidth - margin.left - margin.right;

const height = svgHeight - margin.top - margin.bottom;

// Create SVG container

const svg = d3.select("svg")

.attr("width", svgWidth)

.attr("height", svgHeight);

const chart = svg.append("g")

.attr("transform", `translate(${margin.left}, ${margin.top})`);


// Create scales

const xScale = d3.scaleBand()

.domain(data.map(d => d.label))

.range([0, width])

.padding(0.2);

const yScale = d3.scaleLinear()

.domain([0, d3.max(data, d => d.value)])

.range([height, 0]);

// Draw axes

chart.append("g")

.call(d3.axisLeft(yScale))

.attr("class", "y-axis");

chart.append("g")

.call(d3.axisBottom(xScale))

.attr("class", "x-axis")

.attr("transform", `translate(0, ${height})`);

// Draw bars
chart.selectAll(".bar")

.data(data)

.enter()

.append("rect")

.attr("class", "bar")

.attr("x", d => xScale(d.label))

.attr("y", d => yScale(d.value))

.attr("width", xScale.bandwidth())

.attr("height", d => height - yScale(d.value))

.attr("fill", "steelblue");

// Add text labels to bars

chart.selectAll(".label")

.data(data)

.enter()

.append("text")

.attr("class", "label")

.attr("x", d => xScale(d.label) + xScale.bandwidth() / 2)

.attr("y", d => yScale(d.value) - 5)

.attr("text-anchor", "middle")

.text(d => d.value);

</script>
</body>

</html>

Steps:

This example uses D3.js to create a scalable and customizable column chart. Let
me know if you'd like a similar example using Canvas.js, or if you'd like me to
adjust the chart further

4b. Showing the data as a stacked column chart


To create a stacked column chart, we can use D3.js for flexibility and
customization. Here's an example of how to implement a stacked column chart
based on sample data.

<!DOCTYPE html>

<html>

<head>

<title>Stacked Column Chart with D3.js</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="800" height="500"></svg>

<script>

// Sample data

const data = [
{ label: "January", categoryA: 10, categoryB: 20, categoryC: 30 },

{ label: "February", categoryA: 15, categoryB: 25, categoryC: 20 },

{ label: "March", categoryA: 20, categoryB: 15, categoryC: 35 },

{ label: "April", categoryA: 25, categoryB: 30, categoryC: 15 },

{ label: "May", categoryA: 30, categoryB: 20, categoryC: 25 }

];

// Set dimensions

const svgWidth = 800, svgHeight = 500;

const margin = { top: 20, right: 30, bottom: 50, left: 50 };

const width = svgWidth - margin.left - margin.right;

const height = svgHeight - margin.top - margin.bottom;

// SVG container

const svg = d3.select("svg")

.attr("width", svgWidth)

.attr("height", svgHeight);

const chart = svg.append("g")

.attr("transform", `translate(${margin.left}, ${margin.top})`);

// Stack generator
const stack = d3.stack()

.keys(["categoryA", "categoryB", "categoryC"]);

const stackedData = stack(data);

// Scales

const xScale = d3.scaleBand()

.domain(data.map(d => d.label))

.range([0, width])

.padding(0.2);

const yScale = d3.scaleLinear()

.domain([0, d3.max(data, d => d.categoryA + d.categoryB + d.categoryC)])

.nice()

.range([height, 0]);

const colorScale = d3.scaleOrdinal()

.domain(["categoryA", "categoryB", "categoryC"])

.range(["#6baed6", "#fd8d3c", "#74c476"]);

// Draw axes

chart.append("g")
.call(d3.axisLeft(yScale))

.attr("class", "y-axis");

chart.append("g")

.call(d3.axisBottom(xScale))

.attr("class", "x-axis")

.attr("transform", `translate(0, ${height})`);

// Draw bars

chart.selectAll(".layer")

.data(stackedData)

.enter()

.append("g")

.attr("class", "layer")

.attr("fill", d => colorScale(d.key))

.selectAll("rect")

.data(d => d)

.enter()

.append("rect")

.attr("x", d => xScale(d.data.label))

.attr("y", d => yScale(d[1]))

.attr("height", d => yScale(d[0]) - yScale(d[1]))


.attr("width", xScale.bandwidth());

// Add legend

const legend = svg.append("g")

.attr("transform", `translate(${width + margin.left + 10}, ${margin.top})`);

["categoryA", "categoryB", "categoryC"].forEach((category, i) => {

const legendRow = legend.append("g")

.attr("transform", `translate(0, ${i * 20})`);

legendRow.append("rect")

.attr("width", 15)

.attr("height", 15)

.attr("fill", colorScale(category));

legendRow.append("text")

.attr("x", 20)

.attr("y", 12)

.attr("text-anchor", "start")

.text(category)

.style("font-size", "12px");

});
</script>

</body>

</html>

Steps to Run:

This chart uses D3.js to stack data and create color-coded groups for better
visualization. Let me know if you'd like further enhancements or need help with
Canvas.js!

4c. Showing the Data as a column chart for four age group
Here's how you can create a column chart representing data for four age groups
using D3.js:

<!DOCTYPE html>

<html>

<head>

<title>Age Group Column Chart</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="800" height="500"></svg>

<script>

// Sample data for four age groups

const data = [
{ ageGroup: "0-18", value: 20 },

{ ageGroup: "19-35", value: 35 },

{ ageGroup: "36-50", value: 25 },

{ ageGroup: "51+", value: 15 }

];

// Set chart dimensions

const svgWidth = 800, svgHeight = 500;

const margin = { top: 20, right: 30, bottom: 50, left: 50 };

const width = svgWidth - margin.left - margin.right;

const height = svgHeight - margin.top - margin.bottom;

// Create SVG container

const svg = d3.select("svg")

.attr("width", svgWidth)

.attr("height", svgHeight);

const chart = svg.append("g")

.attr("transform", `translate(${margin.left}, ${margin.top})`);

// Create scales

const xScale = d3.scaleBand()


.domain(data.map(d => d.ageGroup))

.range([0, width])

.padding(0.2);

const yScale = d3.scaleLinear()

.domain([0, d3.max(data, d => d.value)])

.range([height, 0]);

// Draw axes

chart.append("g")

.call(d3.axisLeft(yScale))

.attr("class", "y-axis");

chart.append("g")

.call(d3.axisBottom(xScale))

.attr("class", "x-axis")

.attr("transform", `translate(0, ${height})`);

// Draw bars

chart.selectAll(".bar")

.data(data)

.enter()
.append("rect")

.attr("class", "bar")

.attr("x", d => xScale(d.ageGroup))

.attr("y", d => yScale(d.value))

.attr("width", xScale.bandwidth())

.attr("height", d => height - yScale(d.value))

.attr("fill", "steelblue");

// Add labels to the bars

chart.selectAll(".label")

.data(data)

.enter()

.append("text")

.attr("class", "label")

.attr("x", d => xScale(d.ageGroup) + xScale.bandwidth() / 2)

.attr("y", d => yScale(d.value) - 5)

.attr("text-anchor", "middle")

.text(d => d.value);

</script>

</body>

</html>

Steps to Use:
This example uses D3.js to handle the scales and draw a column chart. It can
easily be extended with interactivity, tooltips, or dynamic data if needed. Let
me know if you'

4d. Showing the data as a Line chart (single, fewer and multiple lines
<!DOCTYPE html>

<html>

<head>

<title>Single Line Chart</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="800" height="500"></svg>

<script>

// Sample data

const data = [

{ month: "Jan", value: 10 },

{ month: "Feb", value: 20 },

{ month: "Mar", value: 15 },

{ month: "Apr", value: 25 },

{ month: "May", value: 30 }


];

// Set dimensions

const svgWidth = 800, svgHeight = 500;

const margin = { top: 20, right: 30, bottom: 50, left: 50 };

const width = svgWidth - margin.left - margin.right;

const height = svgHeight - margin.top - margin.bottom;

// Create SVG container

const svg = d3.select("svg")

.attr("width", svgWidth)

.attr("height", svgHeight);

const chart = svg.append("g")

.attr("transform", `translate(${margin.left}, ${margin.top})`);

// Scales

const xScale = d3.scalePoint()

.domain(data.map(d => d.month))

.range([0, width]);

const yScale = d3.scaleLinear()


.domain([0, d3.max(data, d => d.value)])

.range([height, 0]);

// Draw axes

chart.append("g")

.call(d3.axisLeft(yScale));

chart.append("g")

.attr("transform", `translate(0, ${height})`)

.call(d3.axisBottom(xScale));

// Line generator

const line = d3.line()

.x(d => xScale(d.month))

.y(d => yScale(d.value));

// Draw the line

chart.append("path")

.datum(data)

.attr("fill", "none")

.attr("stroke", "steelblue")

.attr("stroke-width", 2)
.attr("d", line);

</script>

</body>

</html>

2. Line Chart for Fewer Lines Example

Here’s a version for two lines representing two categories:

<!DOCTYPE html>

<html>

<head>

<title>Fewer Lines Chart</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="800" height="500"></svg>

<script>

// Sample data

const data = [

{ month: "Jan", categoryA: 10, categoryB: 15 },

{ month: "Feb", categoryA: 20, categoryB: 25 },

{ month: "Mar", categoryA: 15, categoryB: 30 },

{ month: "Apr", categoryA: 25, categoryB: 20 },


{ month: "May", categoryA: 30, categoryB: 35 }

];

// Set dimensions

const svgWidth = 800, svgHeight = 500;

const margin = { top: 20, right: 30, bottom: 50, left: 50 };

const width = svgWidth - margin.left - margin.right;

const height = svgHeight - margin.top - margin.bottom;

// Create SVG container

const svg = d3.select("svg")

.attr("width", svgWidth)

.attr("height", svgHeight);

const chart = svg.append("g")

.attr("transform", `translate(${margin.left}, ${margin.top})`);

// Scales

const xScale = d3.scalePoint()

.domain(data.map(d => d.month))

.range([0, width]);
const yScale = d3.scaleLinear()

.domain([0, d3.max(data, d => Math.max(d.categoryA, d.categoryB))])

.range([height, 0]);

// Draw axes

chart.append("g")

.call(d3.axisLeft(yScale));

chart.append("g")

.attr("transform", `translate(0, ${height})`)

.call(d3.axisBottom(xScale));

// Line generator

const lineA = d3.line()

.x(d => xScale(d.month))

.y(d => yScale(d.categoryA));

const lineB = d3.line()

.x(d => xScale(d.month))

.y(d => yScale(d.categoryB));

// Draw the lines


chart.append("path")

.datum(data)

.attr("fill", "none")

.attr("stroke", "steelblue")

.attr("stroke-width", 2)

.attr("d", lineA);

chart.append("path")

.datum(data)

.attr("fill", "none")

.attr("stroke", "orange")

.attr("stroke-width", 2)

.attr("d", lineB);

</script>

</body>

</html>

3. Multiple Line Chart Example

If you want multiple lines (3 or more), you can generalize the approach:

<!DOCTYPE html>

<html>

<head>
<title>Multiple Line Chart</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="800" height="500"></svg>

<script>

// Sample data

const data = [

{ month: "Jan", categoryA: 10, categoryB: 15, categoryC: 20 },

{ month: "Feb", categoryA: 20, categoryB: 25, categoryC: 30 },

{ month: "Mar", categoryA: 15, categoryB: 30, categoryC: 25 },

{ month: "Apr", categoryA: 25, categoryB: 20, categoryC: 15 },

{ month: "May", categoryA: 30, categoryB: 35, categoryC: 40 }

];

const keys = ["categoryA", "categoryB", "categoryC"];

// Set dimensions

const svgWidth = 800, svgHeight = 500;

const margin = { top: 20, right: 30, bottom: 50, left: 50 };

const width = svgWidth - margin.left - margin.right;


const height = svgHeight - margin.top - margin.bottom;

// Create SVG container

const svg = d3.select("svg")

.attr("width", svgWidth)

.attr("height", svgHeight);

const chart = svg.append("g")

.attr("transform", `translate(${margin.left}, ${margin.top})`);

// Scales

const xScale = d3.scalePoint()

.domain(data.map(d => d.month))

.range([0, width]);

const yScale = d3.scaleLinear()

.domain([0, d3.max(data, d => Math.max(...keys.map(k => d[k])))])

.range([height, 0]);

const colorScale = d3.scaleOrdinal()

.domain(keys)

.range(["steelblue", "orange", "green"]);


// Draw axes

chart.append("g")

.call(d3.axisLeft(yScale));

chart.append("g")

.attr("transform", `translate(0, ${height})`)

.call(d3.axisBottom(xScale));

// Line generator

const line = d3.line()

.x(d => xScale(d.month))

.y((d, i, group) => yScale(d[group]));

// Draw lines

keys.forEach(key => {

chart.append("path")

.datum(data)

.attr("fill", "none")

.attr("stroke", colorScale(key))

.attr("stroke-width", 2)

.attr("d", d3.line()
.x(d => xScale(d.month))

.y(d => yScale(d[key]))

);

});

// Add legend

const legend = chart.append("g")

.attr("transform", `translate(${width - 100}, 10)`);

keys.forEach((key, i) => {

const legendRow = legend.append("g")

.attr("transform", `translate(0, ${i * 20})`);

legendRow.append("rect")

.attr("width", 15)

.attr("height", 15)

.attr("fill", colorScale(key));

legendRow.append("text")

.attr("x", 20)

.attr("y", 12)

.attr("text-anchor", "start")
.text(key)

.style("font-size", "12px");

});

</script>

</body>

</html>

4e. Showing the data as a Pie Chart (single and multiple pie)
Single Pie Chart Example

<!DOCTYPE html>

<html>

<head>

<title>Single Pie Chart</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="500" height="500"></svg>

<script>

// Sample data for a single pie chart

const data = [

{ label: "Group A", value: 30 },

{ label: "Group B", value: 40 },


{ label: "Group C", value: 20 },

{ label: "Group D", value: 10 }

];

const width = 500;

const height = 500;

const radius = Math.min(width, height) / 2;

// Create SVG container

const svg = d3.select("svg")

.attr("width", width)

.attr("height", height)

.append("g")

.attr("transform", `translate(${width / 2}, ${height / 2})`);

// Create pie and arc generators

const pie = d3.pie().value(d => d.value);

const arc = d3.arc().innerRadius(0).outerRadius(radius);

// Create color scale

const color = d3.scaleOrdinal(d3.schemeCategory10);


// Draw pie chart

svg.selectAll("path")

.data(pie(data))

.enter()

.append("path")

.attr("d", arc)

.attr("fill", d => color(d.data.label))

.attr("stroke", "white")

.style("stroke-width", "2px");

// Add labels

svg.selectAll("text")

.data(pie(data))

.enter()

.append("text")

.attr("transform", d => `translate(${arc.centroid(d)})`)

.attr("text-anchor", "middle")

.text(d => `${d.data.label} (${d.data.value})`)

.style("font-size", "12px");

</script>

</body>

</html>
Multiple Pie Charts Example

To display multiple pie charts, we can generate one for each dataset and
position them side by side.

<!DOCTYPE html>

<html>

<head>

<title>Multiple Pie Charts</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="1000" height="500"></svg>

<script>

// Sample datasets for multiple pie charts

const datasets = [

{ label: "Group A", value: 30 },

{ label: "Group B", value: 40 },

{ label: "Group C", value: 20 },

{ label: "Group D", value: 10 }

],

[
{ label: "Group A", value: 25 },

{ label: "Group B", value: 35 },

{ label: "Group C", value: 25 },

{ label: "Group D", value: 15 }

];

const width = 1000;

const height = 500;

const radius = 150;

// Create SVG container

const svg = d3.select("svg")

.attr("width", width)

.attr("height", height);

const color = d3.scaleOrdinal(d3.schemeCategory10);

datasets.forEach((data, i) => {

const pie = d3.pie().value(d => d.value);

const arc = d3.arc().innerRadius(0).outerRadius(radius);


// Create a group for each pie chart

const pieGroup = svg.append("g")

.attr("transform", `translate(${200 + i * 400}, ${height / 2})`);

// Draw each pie chart

pieGroup.selectAll("path")

.data(pie(data))

.enter()

.append("path")

.attr("d", arc)

.attr("fill", d => color(d.data.label))

.attr("stroke", "white")

.style("stroke-width", "2px");

// Add labels for each pie chart

pieGroup.selectAll("text")

.data(pie(data))

.enter()

.append("text")

.attr("transform", d => `translate(${arc.centroid(d)})`)

.attr("text-anchor", "middle")

.text(d => d.data.label)


.style("font-size", "12px");

});

</script>

</body>

</html>

4f. Showing the data as a Bar Chart (Simple and multiple


Simple Bar Chart

This example creates a single bar chart displaying one set of data.

<!DOCTYPE html>

<html>

<head>

<title>Simple Bar Chart</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="800" height="500"></svg>

<script>

// Sample data

const data = [

{ label: "Jan", value: 30 },

{ label: "Feb", value: 80 },


{ label: "Mar", value: 45 },

{ label: "Apr", value: 60 },

{ label: "May", value: 20 }

];

const width = 800;

const height = 500;

const margin = { top: 20, right: 30, bottom: 50, left: 50 };

const svg = d3.select("svg")

.attr("width", width)

.attr("height", height);

const chartWidth = width - margin.left - margin.right;

const chartHeight = height - margin.top - margin.bottom;

const chart = svg.append("g")

.attr("transform", `translate(${margin.left}, ${margin.top})`);

// Scales

const xScale = d3.scaleBand()

.domain(data.map(d => d.label))


.range([0, chartWidth])

.padding(0.2);

const yScale = d3.scaleLinear()

.domain([0, d3.max(data, d => d.value)])

.range([chartHeight, 0]);

// Axes

chart.append("g")

.call(d3.axisLeft(yScale));

chart.append("g")

.attr("transform", `translate(0, ${chartHeight})`)

.call(d3.axisBottom(xScale));

// Bars

chart.selectAll(".bar")

.data(data)

.enter()

.append("rect")

.attr("class", "bar")

.attr("x", d => xScale(d.label))


.attr("y", d => yScale(d.value))

.attr("width", xScale.bandwidth())

.attr("height", d => chartHeight - yScale(d.value))

.attr("fill", "steelblue");

</script>

</body>

</html>

Grouped (Multiple) Bar Chart

This example creates a grouped bar chart for multiple categories per label.

<!DOCTYPE html>

<html>

<head>

<title>Grouped Bar Chart</title>

<script src="https://d3js.org/d3.v7.min.js"></script>

</head>

<body>

<svg width="800" height="500"></svg>

<script>

// Sample data

const data = [

{ label: "Jan", categoryA: 30, categoryB: 20 },


{ label: "Feb", categoryA: 80, categoryB: 60 },

{ label: "Mar", categoryA: 45, categoryB: 50 },

{ label: "Apr", categoryA: 60, categoryB: 70 },

{ label: "May", categoryA: 20, categoryB: 30 }

];

const width = 800;

const height = 500;

const margin = { top: 20, right: 30, bottom: 50, left: 50 };

const svg = d3.select("svg")

.attr("width", width)

.attr("height", height);

const chartWidth = width - margin.left - margin.right;

const chartHeight = height - margin.top - margin.bottom;

const chart = svg.append("g")

.attr("transform", `translate(${margin.left}, ${margin.top})`);

const categories = ["categoryA", "categoryB"];


// Scales

const xScale = d3.scaleBand()

.domain(data.map(d => d.label))

.range([0, chartWidth])

.padding(0.2);

const xSubScale = d3.scaleBand()

.domain(categories)

.range([0, xScale.bandwidth()])

.padding(0.1);

const yScale = d3.scaleLinear()

.domain([0, d3.max(data, d => Math.max(d.categoryA, d.categoryB))])

.range([chartHeight, 0]);

const colorScale = d3.scaleOrdinal()

.domain(categories)

.range(["steelblue", "orange"]);

// Axes

chart.append("g")

.call(d3.axisLeft(yScale));
chart.append("g")

.attr("transform", `translate(0, ${chartHeight})`)

.call(d3.axisBottom(xScale));

// Bars

chart.append("g")

.selectAll("g")

.data(data)

.enter()

.append("g")

.attr("transform", d => `translate(${xScale(d.label)}, 0)`)

.selectAll("rect")

.data(d => categories.map(category => ({ key: category, value: d[category]


})))

.enter()

.append("rect")

.attr("x", d => xSubScale(d.key))

.attr("y", d => yScale(d.value))

.attr("width", xSubScale.bandwidth())

.attr("height", d => chartHeight - yScale(d.value))

.attr("fill", d => colorScale(d.key));


</script>

</body>

</html>

exp5. Develop Following Program Using HTML5 and Google Chats API and
Map API
To create a program using HTML5, Google Chat API, and Google Maps API,
you need to integrate both APIs into your web application for specific
functionality like handling messages and visualizing location data.
Below is a simple example illustrating the integration of Google Maps API
(for map rendering) and Google Chat API (mockup of message handling). For
Google Chat API, you will need access to the API via Google Cloud Console
and proper authentication.

Example Program
<!DOCTYPE html>

<html>

<head>

<title>Google Maps and Chat Integration</title>

<style>

#map {

height: 400px;

width: 100%;

body {

font-family: Arial, sans-serif;

}
</style>

<script src="https://maps.googleapis.com/maps/api/js?
key=YOUR_API_KEY"></script>

</head>

<body>

<h2>Google Maps and Chat Integration</h2>

<!-- Input Message Area -->

<div>

<h4>Send a Message:</h4>

<textarea id="messageInput" rows="4" cols="50" placeholder="Type your


message here"></textarea><br>

<button onclick="sendMessage()">Send</button>

</div>

<!-- Display Messages -->

<div>

<h4>Messages:</h4>

<ul id="messageList"></ul>

</div>

<!-- Map Section -->


<h4>Map Location:</h4>

<div id="map"></div>

<script>

// Initialize Google Map

function initMap() {

const defaultLocation = { lat: 37.7749, lng: -122.4194 }; // San Francisco,


CA

const map = new google.maps.Map(document.getElementById("map"), {

zoom: 12,

center: defaultLocation,

});

// Add a marker to the default location

new google.maps.Marker({

position: defaultLocation,

map: map,

title: "Default Location",

});

// Initialize the map when the window loads


window.onload = initMap;

// Mock Google Chat API Integration

function sendMessage() {

const message = document.getElementById("messageInput").value;

if (message.trim() !== "") {

// Append the message to the chat list

const messageList = document.getElementById("messageList");

const li = document.createElement("li");

li.textContent = message;

messageList.appendChild(li);

// You can send the message to Google Chat API here (example mock
function)

console.log("Sending message to Google Chat API:", message);

// Clear the input field

document.getElementById("messageInput").value = "";

} else {

alert("Please enter a valid message.");

}
</script>

</body>

</html>

You might also like