0% found this document useful (0 votes)
22 views136 pages

Google Charts API: Data Visualization Guide

Google Charts is a free web-based data visualization library developed by Google that allows developers to create interactive and customizable charts using HTML5/SVG technology and JavaScript. It supports a wide variety of chart types, is highly customizable, and can integrate data from various sources. The document also discusses the application of Google Charts in industries like healthcare, food, and aviation, highlighting its benefits and providing examples of chart types for different use cases.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views136 pages

Google Charts API: Data Visualization Guide

Google Charts is a free web-based data visualization library developed by Google that allows developers to create interactive and customizable charts using HTML5/SVG technology and JavaScript. It supports a wide variety of chart types, is highly customizable, and can integrate data from various sources. The document also discusses the application of Google Charts in industries like healthcare, food, and aviation, highlighting its benefits and providing examples of chart types for different use cases.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Course Contents

 Google Charts
 Google Charts API
 Chart Animations
What is Google Charts?
 Google Charts is a free, web-based data visualization library
developed by Google. It enables developers to create
interactive, customizable, and responsive charts using
HTML5/SVG technology — with simple JavaScript.
 Google Charts helps transform raw data into visually
appealing and easy-to-understand graphs, making it ideal
for use in dashboards, reports, or web apps.
 Launched by: Google
Written in: JavaScript
Used for: Visualizing data in a web browser
Features of Google Charts:
 Wide variety of chart types: line, bar, pie, scatter, area, geo charts,
gauges, timelines, and more.
 Highly customizable: colors, fonts, labels, tooltips, legends,
animation.
 Interactive: supports zoom, pan, hover effects, drill-downs.
 Data integration: works with JSON, CSV, Google Sheets, or manual
data input.
 Responsive: adapts to different screen sizes.
 Cross-browser compatibility.
Advantages of Google Charts:
 Free and Easy to Use
 Wide Range of Chart Types
 Highly Customizable
 Interactive and Responsive
 Easy Integration with Web Technologies
 Cross-Browser Compatibility
 No Installation Required
 Regular Updates and Support
Steps required to create a chart using Google
Charts

Load the Draw


Set a Create Define Instantiate
Google
Charts
callback the data chart the chart the
function table options object
library chart
How to Use Google Chart?
1. Add a <div> element (with a unique id) in the HTML where you want to display the chart:

<div id="myChart" style="max-width:700px; height:400px"></div>

2. Add a link to the charts loader:

<script src="[Link]
3. Load the Graph API, and add the function to run when the API is loaded:

<script>
[Link]('current',{packages:['corechart']});
[Link](drawChart);

// Your Function
function drawChart() {
...
}
</script>
Bar Charts
<!DOCTYPE html> ['Spain',44],
<html> ['USA',24],
<script ['Argentina',15]
src="[Link]
]);
</script>
// Set Options
<body>
const options = {
<div id="myChart" style="width:100%; max-
width:600px; height:500px;"></div> title:'World Wide Wine Production'
<script> };
[Link]('current', // Draw
{'packages':['corechart']});
const chart = new
[Link](drawChart); [Link](document.
function drawChart() { getElementById('myChart'));
// Set Data [Link](data, options);
const data = }
[Link](
</script>
[['Contry', 'Mhl'],
</body>
['Italy',55],
</html>
['France',49],
Pie chart:
<html> ['USA',23.9],
<script ['Argentina',14.5]
src="[Link] ]);
"></script> // Set Options
<body> const options = {
<div title:'World Wide Wine Production',
id="myChart" style="width:100%; max- is3D:true
width:600px; height:500px;"> };
</div> // Draw
<script> const chart = new
[Link]('current', [Link](document.
{'packages':['corechart']}); getElementById('myChart'));
[Link] [Link](data, options);
(drawChart); }
function drawChart() { </script>
// Set Data </body>
const data = </html>
[Link]([
['Contry', 'Mhl'],
['Italy',54.8],
['France',48.6],
['Spain',44.4],
Line Graph
<!DOCTYPE html> // Set Options
<html> const options = {
<script title: 'House Prices vs. Size',
src="[Link] hAxis: {title: 'Square Meters'},
"></script> vAxis: {title: 'Price in Millions'},
<body> legend: 'none'
<div id="myChart" style="width:100%; max- };
width:600px; height:500px;"></div> // Draw
<script> const chart = new
[Link]('current',{packages: [Link](document.
['corechart']}); getElementById('myChart'));
[Link](drawChart); [Link](data, options);
function drawChart() { }
// Set Data </script>
const data = </body>
[Link]([ </html>
['Price', 'Size'],
[50,7],[60,8],[70,8],[80,9],[90,9],
[100,9],[110,10],[120,11],
[130,14],[140,14],[150,15]]);
Scatter Chart:
<!DOCTYPE html> // Set Options
<html> const options = {
<script title: 'House Prices vs. Size',
src="[Link]
ript> hAxis: {title: 'Square Meters'},
vAxis: {title: 'Price in Millions'},
<body>
<div id="myChart" style="width:100%; max- legend: 'none'
width:600px; height:500px;"></div> };
<script> // Draw
[Link]('current',{packages:['corechart']}) const chart = new
; [Link](document.
[Link](drawChart); getElementById('myChart'));
function drawChart() { [Link](data, options);
// Set Data }
const data = [Link]([ </script>
['Price', 'Size'], </body>
[50,7],[60,8],[70,8],[80,9],[90,9], </html>
[100,9],[110,10],[120,11],
[130,14],[140,14],[150,15]]);
Candlestick Chart
<html> ['Fri', 68, 66, 22, 15]
<head> // Treat first row as data as well.
<title>Google Charts Tutorial</title> ], true);
<script type = "text/javascript" src = // Set chart options
"[Link] var options = {legend: 'none'};
</script> // Instantiate and draw the chart.
<script type = "text/javascript"> var chart = new
[Link]('current', {packages: [Link](
['corechart']}); [Link]('container'));
</script> [Link](data, options);
</head> }
<body> [Link](drawChart);
<div id = "container" style = "width: 550px; </script>
height: 400px; margin: 0 auto"> </body>
</div> </html>
<script language = "JavaScript">
function drawChart() {
// Define the chart to be drawn.
var data =
[Link]([
['Mon', 20, 28, 38, 45],
['Tue', 31, 38, 55, 66],
['Wed', 50, 55, 77, 80],
['Thu', 77, 77, 66, 50],
What is the Google Chart API ?
 The Google Chart API is an extremely simple tool that lets you easily
create a chart from some data and embed it in a webpage. You embed
the data and formatting parameters in an HTTP request, and Google
returns a PNG image of the chart.
 Many types of chart are supported, and by making the request into
an image tag you can simply include the chart in a webpage
Google Charts API can be used in the airline industry
The Google Charts API can be used in the airline industry to visualize various data points, providing
insights into operations, customer behavior, and market trends. While the Google Charts API itself is
free to use, accessing specific airline data might require integration with other APIs, some of which
may have associated costs or free tiers depending on usage.

Google Charts could be used to visualize airline data:

 Flight Performance Dashboard:


 Chart Type: Line Chart or Area Chart
 Data: On-time performance percentages, average delay times, cancellation rates over a
period.
 Visualization: A line chart showing the trend of on-time performance for a specific airline or
route, or an area chart illustrating the proportion of delayed vs. on-time flights.
 Route Popularity & Revenue Analysis:
 Chart Type: Bar Chart or Column Chart
 Data: Number of passengers per route, revenue generated per route, load factors.
 Visualization: A bar chart comparing the passenger volume or revenue across different
routes, allowing for easy identification of high-performing and underperforming routes.
 Customer Feedback & Sentiment Analysis:
Chart Type: Pie Chart or Donut Chart
Data: Distribution of customer satisfaction ratings (e.g., highly satisfied, satisfied, neutral,
dissatisfied), breakdown of feedback categories (e.g., service, comfort, punctuality).
Visualization: A pie chart showing the percentage of customers in each satisfaction
category or a donut chart illustrating the proportion of different feedback types.
 Aircraft Utilization:
Chart Type: Gauge Chart or Table Chart
Data: Average flight hours per aircraft, maintenance schedules, availability rates.
Visualization: A gauge chart showing the current utilization percentage of a specific aircraft
type, or a table chart summarizing the maintenance status of the entire fleet.
Data acquisition (free options)
 Google Flights: Provides a robust API for flight search and pricing data, which can
be scraped for charting purposes.
 Travel Impact Model API: Offered by Google for Developers, this API provides
flight emission estimates, which could be interesting to analyze alongside other
airline data.
 OpenSky Network: A community-driven project that shares real-time and
historical flight data from aircraft globally.
 Bureau of Transportation Statistics (US specific): Offers detailed statistics on
flight performance, service quality, and operational aspects of US aviation.
 Flightradar24: While primarily a flight tracking service, it also offers a large
aviation database with historical data that could be leveraged.
Benefits of Google flight API Integration:
 Google Flight API integration helps travellers to search for and book flights. It
also controls the accessibility as specified by the traveller.
 Google Flight API integration includes all relevant data, such as prices, discounts,
offers, deals, and availability.
 Google Flight API integration connect airline service providers all over the world.
This allows travellers to compare the prices and deals offered by various airline
service providers.
Chart Type Example Use Case

Pie Chart Passenger distribution by cabin class (Economy, Business, First)

Geo Chart Flight route heatmaps across regions or countries

Bar Chart On-time performance comparison between airlines

Scatter Chart Correlation between flight distance and delays

Gauge Chart Airport security wait times or baggage handling speed


Demonstrating Google Charts API in the healthcare
industry
Why Use Google Charts in Healthcare?
 Real-time dashboards for hospital management.
 Interactive and dynamic visualizations.
 Easy integration with EMR/EHR systems.
 Cost-effective: it's free.
Data acquisition (free options and considerations)
 Publicly Available Datasets: Many government agencies and research institutions offer
open healthcare datasets. Examples include:
1. CDC (Centers for Disease Control and Prevention): Provides data on various health
topics, diseases, and demographics.
2. WHO (World Health Organization): Offers global health statistics and data.
3. NHS Digital (UK specific): Provides health and social care data for England.
 De-identified Clinical Data: While direct access to patient-level data is strictly regulated
(e.g., HIPAA compliance in the US), Cloud Healthcare API supports de-identifying data
for research and analysis. This allows organizations to leverage their own data for
visualization while maintaining patient privacy.
Chart Type Healthcare Example

Pie Chart Patient gender distribution

Line Chart COVID-19 case trends over time

Gauge Chart ICU bed occupancy rate

Geo Chart Disease outbreak hotspots by region

Timeline Patient treatment history or surgery schedules


Demonstrating Google Charts API in the
food industry
The food industry, spanning from farm to fork, generates vast amounts of data. Google Charts
API can be effectively used to visualize this data and derive valuable insights, impacting
various areas like production, sales, nutrition, and supply chain management.

Data acquisition (free options and considerations)


 Publicly available food datasets: Organizations like the USDA (US Department of
Agriculture) provide extensive databases on food composition, nutrient values, and
agricultural production according to [Link].

 Restaurant sales data (simulated/aggregated): While real-time sales data might be


proprietary, simulated or aggregated datasets can be used to demonstrate sales trends,
peak hours, or popular dishes.

 Google Business Profile API: If you're a food business owner, you can use the Google
Business Profile API to access and update information like food menus and related
attributes (allergens, dietary restrictions). This data can then be visualized using Google
Charts.

 Food Allergy and Allergen data: Resources like Food Allergy Training provide information
on food allergen menu matrices which can be converted to data for charting.
Choosing a chart type
The choice of chart depends on the specific aspect of the food industry you want
to analyze:
 Pie charts/Donut charts: To visualize the breakdown of menu item categories,
ingredient proportions, or customer preferences. Market share of different
food brands

 Column charts/Bar charts: For comparing sales performance across different


product lines, restaurant locations, or time periods. Customer ratings
comparison for different dishes

 Line charts: To track trends over time, like food consumption patterns,
ingredient prices, or inventory levels.

 Table charts: To display detailed nutritional information or allergen lists in a


structured format.

 Gauge charts: To show real-time metrics, such as food temperature in storage


or delivery vehicle temperatures. Real-time kitchen inventory or order
fulfillment rate

 Geocharts: To visualize the geographical distribution of food origins,


consumption patterns, or delivery routes.
Chart Animations

 Chart animations in Google Charts refer to the visual


transition effects applied to charts when they are
drawn or updated. These animations can include effects
such as elements fading in, growing from zero size, or
sliding into place.
 Animations enhance the visual experience by gradually
introducing changes, making the chart more engaging
and easier to understand.
Purpose of Using Chart Animations

1
• Enhanced User Experience

2
• Better Data Understanding

3
• Dynamic Data Visualization

4
• Professional Presentation

5
•Useful for Emphasis and Storytelling
Chart animations for the Covid-19 application
case study.

In a Covid-19 application, Line Charts are especially useful to


show how values change over time—such as tracking the number
of daily or monthly cases, recoveries, and deaths

Purpose of Animation in Line Charts:


 To show the growth or decline trends in Covid-19 cases.
 To highlight sudden increases or improvements over time.
 To make the chart more engaging and informative.
Line Chart with Animation
<!DOCTYPE html> animation: {

<html> startup: true,

<head> duration: 1500,

<script type="text/javascript" easing: 'inAndOut'


src="[Link]
},
<script type="text/javascript">
hAxis: { title: 'Month' },
[Link]('current', {'packages':['corechart']});
vAxis: { title: 'Number of People' },
[Link](drawChart);
colors: ['#e74c3c', '#27ae60', '#7f8c8d'],

legend: { position: 'bottom' }


function drawChart() {
};
var data = [Link]([
var chart = new
['Month', 'Confirmed', 'Recovered', 'Deaths'], [Link]([Link](
'covid_line_chart'));
['Jan', 50000, 10000, 2000],
[Link](data, options); }
['Feb', 120000, 40000, 5000],
</script>
['Mar', 250000, 150000, 8000],
</head>
['Apr', 350000, 280000, 12000],
<body>
['May', 400000, 370000, 15000]
<h2>Covid-19 Case Trends (Animated Line Chart)</h2>
]);
<div id="covid_line_chart" style="width: 900px; height:
var options = { 500px;"></div>
title: 'Covid-19 Monthly Case Trends', </body>
curveType: 'function', </html>
Benefits in the Covid-19 Case Study:
 Easily compare multiple data sets (cases, recoveries, deaths).
 Identify spikes in confirmed cases or steady recovery trends.
 Make the dashboard visually intuitive and easy to understand
for the general public.

Conclusion:
 Using an animated Line Chart in a Covid-19 case study allows
 Better communication of time-based trends.
 Improved user experience through interactivity.
 Clearer visual impact when presenting important health data
Chart animations for the World population
analysis case study
 Bar charts are ideal for comparing population data between
countries in a horizontal layout.
 Using animated bar charts makes the trends more readable,
especially when dealing with large numbers and multi-
country comparisons over time.
Why Use Animated Bar Charts in Population Studies?
 Bar charts clearly show which country has more or less
population.
 Animations make the transition between years smoother and
more understandable.
 Helps identify trends such as population growth or slowing
growth rates.
Bar Chart with Animation
<!DOCTYPE html> easing: 'out'

<html> },

<head> bars: 'horizontal', // For Bar Chart

<script type="text/javascript" hAxis: { title: 'Population (millions)' },


src="[Link]
vAxis: { title: 'Country' },
<script type="text/javascript">
colors: ['#2ecc71', '#3498db', '#e74c3c', '#9b59b6'],
[Link]('current', {'packages':['corechart']});
legend: { position: 'top', maxLines: 3 }
[Link](drawChart);
};
function drawChart() {
var chart = new
var data = [Link]([ [Link]([Link](

['Country', '2000', '2010', '2020', '2030'], 'population_bar_chart'));

['India', 1050, 1230, 1380, 1500], [Link](data, options);

['China', 1260, 1340, 1410, 1450], }

['USA', 282, 309, 331, 350], </script>

['Brazil', 175, 195, 212, 220] </head>

]); <body>

var options = { <h2>Animated World Population Bar Chart</h2>

title: 'World Population by Country (in millions)', <div id="population_bar_chart" style="width: 1000px;
height: 500px;"></div>
animation: {
</body>
startup: true,
</html>
duration: 2000,
Real-World Application:
 Used by UN, World Bank, and demographic researchers.
 Helps policymakers visualize population pressure and growth
challenges.
 Useful in interactive reports, dashboards, and classroom
teaching.
Conclusion:
Animated bar charts in world population analysis allow for:
 Clear comparison of country-wise population changes.
 Easy understanding of trends over time.
 Enhanced visual engagement with statistical data.
Questions:
 Discuss the advantages of Google Chart.
 Demonstrate Google chart API in Airline industry.
 Demonstrate Google chart API in Food industry.
 Demonstrate Google chart API in HealthCare industry.
 Demonstrate chart animations for the Covid-19 application case study
 Demonstrate chart animations for the World population analysis case
study
 What are chart animations in Google Charts, and why are they used?
 List and explain the steps required to create a chart using Google Charts.
Course Contents
[Link]:
 Making Selections,
 Changing Selection’s Attribute,
 Loading and Filtering External Data,
 Data Formats Usable with D3,
 Creating a Server to Upload Data,
 D3’s Function for Loading Data, Dealing with Asynchronous
Requests,
 Loading and Formatting Large Data Sets
Making Charts Interactive and Animated:
Data Joins, Updates and Exits, Interactive Buttons,
Updating Charts, Adding Transactions, Using Keys
[Link]
 D3 stands for Data-Driven Documents. It is an open-source JavaScript
library developed by Mike Bostock to create custom interactive data
visualizations in the web browser using SVG, HTML and CSS.

 Why Do We Need [Link]?

[Link] is one of the premier framework when compare to other libraries.


This is because it works on the web and its data visualizations are par
excellence. Another reason it has worked so well is owing to its
flexibility. Since it works seamlessly with the existing web technologies
and can manipulate any part of the document object model, it is as
flexible as the Client Side Web Technology Stack (HTML, CSS, and
SVG). It has a great community support and is easier to learn.
D3 Features
 Uses Web Standards: D3 is an extremely powerful visualization tool to create interactive data
visualizations. It exploits the modern web standards: SVG, HTML and CSS to create data
visualization.
 Data Driven: D3 is data driven. It can use static data or fetch it from the remote server in different
formats such as Arrays, Objects, CSV, JSON, XML etc. to create different types of charts.
 DOM Manipulation: D3 allows you to manipulate the Document Object Model (DOM) based on
your data.
 Data Driven Elements: It empowers your data to dynamically generate elements and apply
styles to the elements, be it a table, a graph or any other HTML element and/or group of
elements.
 Dynamic Properties: D3 gives the flexibility to provide dynamic properties to most of its
functions. Properties can be specified as functions of data. That means your data can drive your
styles and attributes.
 Types of visualization: With D3, there are no standard visualization formats. But it enables you
to create anything from an HTML table to a Pie chart, from graphs and bar charts to geospatial
maps.
 Custom Visualizations: Since D3 works with web standards, it gives you complete control over
your visualization features.
 Transitions: D3 provides the transition() function. This is quite powerful because internally, D3
works out the logic to interpolate between your values and find the intermittent states
 Interaction and animation: D3 provides great support for animation with functions like
duration(), delay() and ease(). Animations from one state to another are fast and responsive to
user interactions.
Advantages of D3
 [Link] is a Javascript library. So, it can be used with any JS framework of your choice like
[Link], [Link] or [Link].

 D3 focuses on data, so it is the most appropriate and specialized tool for data visualizations.

 D3 is open-source. So you can work with the source code and add your own features.

 It works with web standards so you don't need any other technology or plugin other than a
browser to make use of D3

 D3 works with web standards like HTML, CSS and SVG, there is no new learning or
debugging tool required to work on D3.

 D3 does not provide any specific feature, so it gives you complete control over your
visualization to customize it the way you want. This gives it an edge over other popular tools
like Tableau or QlikView.

 Since D3 is lightweight, and works directly with web standards, it is extremely fast and works
well with large datasets.

 It can create dynamic, real-time transformation by manipulating DOM elements, quickly into
data visualization without any latency.

 It works on data and is specialized and appropriate with data visualization functions
contained in the JavaScript library.
Drawbacks of [Link]
 Compatibility issues: [Link] may not fully support older browser
versions, leading to inconsistent rendering or functionality across
platforms.
 Security challenges: [Link] lacks built-in mechanisms for data
encryption or access control, potentially exposing sensitive
information to unauthorized access.
 Design limitations: Crafting visually appealing and innovative
graph designs can be challenging due to [Link]'s complex syntax
and structure.
 Steep learning curve: [Link] requires a significant learning curve,
making it difficult for beginners to grasp advanced concepts and
techniques.
 Performance overhead: Implementing complex visualizations with
[Link] can sometimes result in performance issues, especially on
resource-constrained devices or browsers.
Setting setup with D3
 Download [Link] from

[Link]

 Put the js file in the same directory, where you are creating your other
files and

use <script src="[Link]"></script>

OR

 Use the [Link] from [Link]. Use the following in your html file

<script src="[Link] is preferred


Editor
 Visual Studio Code
 WebStorm
 Eclipse
 SublimeText
 These IDEs provide intelligent code completion as well as
support some of the modern JavaScript frameworks.
 Online platforms like CodePen and JSFiddle are popular choices.
Making selections-using DOM
Modifying documents using the W3C DOM API is tedious: the
method names are verbose, and the imperative approach
requires manual iteration and bookkeeping of temporary
state.
For example, to change the text color of paragraph elements:
var paragraphs = [Link]("p");
for (var i = 0; i < [Link]; i++) {
var paragraph = [Link](i);
[Link]("color", "blue", null);
}
Making selections
 [Link] helps to select elements from the HTML page using the
following two methods −
 select() − Selects only one DOM element by matching the given
CSS selector. If there are more than one elements for the given
CSS selector, it selects the first one only.
 selectAll() − Selects all DOM elements by matching the given CSS
selector. If you are familiar with selecting elements with jQuery,
[Link] selectors are almost the same.
Making selections
 D3 employs a declarative approach, operating on arbitrary sets of
nodes called selections.
 For example, you can rewrite the above loop as:
[Link]("p").style("color", "blue");
 Yet, you can still manipulate individual nodes as needed:
[Link]("body").style("background-color", "black");
 Selectors are defined by the W3C Selectors API and supported
natively by modern browsers.
 The above examples select nodes by tag name ("p" and "body",
respectively).
 Elements may be selected using a variety of predicates, including
containment, attribute values, class and ID
Changing selection’s attribute
 All <p> tags attribute value change
[Link]("p").style("color", "red");
 Changing individual attribute value
[Link]("body").style("background-color", "white");
Changing selection’s attribute
 All pags attribute value change
[Link]("p").style("color", "white");
 Changing individual attribute value
[Link]("body").style("background-color", "#0000ff")
Changing selection’s attribute
The select() method

The select() method selects the HTML element based on CSS


Selectors. In CSS Selectors, you can define and access HTML-
elements in the following three ways −
1. Tag of a HTML element (e.g. div, h1, p, span, etc.,)
2. Class name of a HTML element
3. ID of a HTML element
Selection by Tag
 Syntax is used to select the div tag elements,
[Link](div)
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "[Link]
</head>
<body>
<div> Hello World! </div>
<script> [Link]("div").text(); </script>
</body>
</html>
OUTPUT:
Hello World!
Selection by Class name
Syntax:
[Link](.<class name>)
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "[Link]
</head>
<body>
<div class = "myclass">
Hello World!
</div>
<script>
[Link](".myclass").text();
</script>
</body>
</html>
OUTPUT:
Hello World!
Selection by ID
Syntax
[Link](#<id of an element>)
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "[Link]
</head>
<body>
<div id = "hello">
Hello World!
</div>
<script>
[Link]("#hello").text();
</script>
</body>
</html>
OUTPUT:
Hello World!
Adding DOM Elements
[Link] selection provides the append() and the text() methods
to append new elements into the existing HTML documents.
The append() Method
• The append() method appends a new element as the last child
of the element in the current selection.
• This method can also modify the style of the elements, their
attributes, properties, HTML and text content.
<div class = "myclass">
Hello World!
</div>
<script>
[Link]("[Link]").append("span");
</script>
The text() Method
 The text() method is used to set the content of the
selected / appended elements.
<div class = "myclass">
Hello World!
</div>
<script>
[Link]("[Link]").append("span").text("from [Link]");
</script>
Hello World! from [Link]
Modifying Elements
[Link] provides various methods, html(), attr() and style() to
modify the content and style of the selected elements.
The html() Method
 The html() method is used to set the html content of the
selected / appended elements.
<div class = "myclass">
Hello World!
</div>
<script>
[Link](".myclass").html("Hello World! <span>from
[Link]</span>");
</script>
Hello World! from [Link]
 The attr() Method
The attr() method is used to add or update the attribute of the
selected elements.
<div class = "myclass">
Hello World!
</div>
<script>
[Link](".myclass").attr("style", "color: red");
</script>
Hello World!
The style() Method
The style() method is used to set the style property of the selected
elements.
<div class = "myclass">
Hello World!
</div>
<script>
[Link](".myclass").style("color", "red");
</script>
Hello World!
The classed() Method
 The classed() method is exclusively used to set the class
attribute of an HTML element.
 Since, a single HTML element can have multiple classes; we
need to be careful while assigning a class to an HTML element.
 This method knows how to handle one or many classes on an
element, and it will be performant.
Add class − To add a class, the second parameter of the classed
method must be set to true.
• It is defined below −
[Link](".myclass").classed("myanotherclass", true);
Remove class − To remove a class, the second parameter of the
classed method must be set to false. It is defined below
[Link](".myclass").classed("myanotherclass", false);
 Check class − To check for the existence of a class, just leave
off the second parameter and pass the class name you are
querying. This will return true, if it exists, false, if it does not.
[Link](".myclass").classed("myanotherclass");
This will return true, if any element in the selection has the class.
Use [Link] for single element selection.
 Toggle class − To flip a class to the opposite state remove it if it
exists already, add it if it does not yet exist you can do one of
the following.
For a single element, the code might look as shown below −
var element = [Link](".myclass")
[Link]("myanotherclass",
![Link]("myanotherclass"));
The selectAll() Method
 The selectAll() method is used to select multiple elements in
the HTML document.
 The select method selects the first element, but the selectAll
method selects all the elements that match the specific
selector string.
 In case the selection matches none, then it returns an
empty selection.
 We can chain all the appending modifying
methods, append(), html(), text(), attr(), style(), classed(), etc.,
in the selectAll() method as well.
 In this case, the methods will affect all the matching
elements
<body>
<h2 class = "myclass">Message</h2>
<div class = "myclass">
Hello World!
</div>
<script>
[Link](".myclass").attr("style", "color: red");
</script>
</body>
Message
Hello World!
Select Nested Elements
The select() and selectAll() method can be used to select nested elements as
shown
<table> Four
<tr> </td>
<td> </tr>
One </table>
</td> <script>
[Link]("tr").selectAll("td").style('backgrou
<td>
nd-color','yellow');
Two
</script>
</td>
</tr>
<tr>
<td>
Three
</td>
<td>
Prerequisites To Learn [Link]
 Text editor: A text editor such as Notepad++ or Vim is needed to
write programming code like HTML, CSS, JavaScript, and integrate
them to produce the desired requirement.
 Web browser: Any one of the modern web browsers, such as Firefox,
Google Chrome, Safari, Opera, or IE9 should be installed to check
and verify the output that is produced after integrating the code.
 HTML: Good understanding of HTML tags and structure will help to
build a basic web page and align elements to bring visualization to
the next level.
 CSS: Cascading Style Sheet (CSS) is used to apply styles including
design, layout, and screen size to web pages.
Prerequisites To Learn [Link]
 DOM: Strong understanding of Document Object Model (DOM) is
essential as it will be easier to know the structure and content of
web documents, access DOM elements for [Link] for data
visualization.
 JavaScript: Familiarity of fundamentals and JavaScript Objects is a
prerequisite for learning and implementing [Link] into our application
so that data visualization can be viewed in the webserver.
 Web Server: It is essential to have a web server installed like Apache
Tomcat or IIS (Internet Information Services) server, so that data can
be uploaded externally in an array, object, XML, CSV, JSON formats
and can be transformed with the help of [Link] into visualization
formats such as graphs, charts, and geospatial visualization.
Loading External data

 D3 can handle different types of data defined either locally in


variables or from external files.
 D3 methods to load different types of data from external files
Method Description
[Link]() Sends http request to the specified url to load .csv file or
data and executes callback function with parsed csv data
objects.
[Link]() Sends http request to the specified url to load .json file
or data and executes callback function with parsed json
data object
Loading External data
 D3 can handle different types of data defined either locally in
variables or from external files.
 D3 methods to load different types of data from external files
Method Description
[Link]() Sends http request to the specified url to load .html file or
data and executes callback function with parsed html data
objects.
[Link]() Sends http request to the specified url to load .text file or
data and executes callback function with parsed text data
objects
Loading external data

 D3 can handle different types of data defined either locally in


variables or from external files.
 D3 methods to load different types of data from external files.
Method Description
[Link]() Sends http request to the specified url to load a .tsv file
or data and executes callback function with parsed tsv
data objects.
[Link]() Sends http request to the specified url to load an .xml
file or data and executes callback function with parsed
xml data objects
Load csv file

 Method: [Link](url[, row, callback]);


 [Link] file
Name, Age
Ami,16
Chiku,12
Baku,10
Load csv file
<!DOCTYPE html>
<html>
<head>
<title>Load CSV data</title>
<script type="text/javascript"
src="[Link]"></script>
</head>
<body>
<script type="text/javascript">
[Link]("[Link]", function(data) {
[Link](data)
})
</script>
</body></html>
Add this in <head> tag
<link rel="icon" type="image/x-icon" href="/[Link]">
Load XML data:
[Link] file
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
<Name>John</Name>
<Age>30</Age>
</row>
<row>
<Name>Jane</Name>
<Age>32</Age>
</row>
</root>
Load XML data
<!DOCTYPE html>
<html>
<head>
<title>Load XML data</title>
<script type="text/javascript"
src="[Link]
</head>
<body>
<script type="text/javascript">
[Link]("[Link]", function(data) {
[Link](data);
});
</script></body></html>
Load XML data:Output
Load Json Data :
json file: {
[Link] "name": "Sup",

[{ "age": 42,
"name": "Ami", "location": "Singapore"

"age": 10, },

"location": "India" {
}, "name": "Viks",

{ "age": 40,
"name": "Eva", "location": "Germany"
"age": 12, }]
"location": "USA"
}
Load json data and print on web page
 The [Link]() method returned a formatted data object. It also
returned an argument "error"
[Link]("/data/[Link]", function(error, data) {
 The output we want to put on our page in body tag
[Link]("body")
 We choose output data in <p> tag.
.selectAll("p")
 We bind the data and pass to next line of code
.data(data)
 enter() Function receives the values from data function, but we haven’t
referenced the <p> tag, it returns empty placeholder references to the
new elements.
.enter()
Load json data and print on web page
 We now have the references to our elements. The append()
method adds these elements to the DOM.
append("p")
 Most d3 functions accept functions as parameters. we have
passed an anonymous function to the text method that returns a
concatenation of name and location from our data object.
 text() is called and bound to each of our page elements with the
corresponding data value.
.text(function(d) { return [Link] + ", " + [Link]; });
 If we want to handle error, we can write,
if (error) {
return [Link](error);
}
D3 code to load and print json Data
<script type="text/javascript">
[Link]("[Link]", function(error, data) {
[Link]()
[Link]("body")
.selectAll("p")
.data(data)
.enter()
.append("p")
.text(function(d) {
return [Link] + "::: " + [Link];
});
});
</script>
JSON data output
Load Text Data:
text file
Ami <head>
Ash <script src=
Hetu "[Link]
Betu </script>
</head>
<body>
<script>
[Link]("[Link]", function (d) {
[Link](d);
});
</script>
</body>
Load Text Data: Output
Filtering the data
 [Link] [Link]() Function is used to filter the data
 The [Link]() function in [Link] is used to filter the
given selection and return a new selection for which the
filter is true. The filter to be used may be a string or a
function.
 Syntax:
[Link](filter);
 Parameters: This function accepts one parameter as
mentioned above and described below:
 filter: It is a string or a function that would be used to filter a
selection. The filter is applied to each selected element
when using a function.
 Return Values: This function returns the new selection
Filtering the data
<!DOCTYPE html>
<html lang="en">
<head>
<script src=
"[Link]
</script>
<script src=
"[Link]
</script>
</head>
</html>
Filtering the data: odd rows
<body> <div>
<b>1. This text is in bold</b>
<b>2. This text is also in bold</b>
<b>3. CKPCET</b>
<b>4. Computer Engineering</b>
<b>5. Data visualization</b>
</div><script>
let selection = [Link]("b")
.filter(":nth-child(odd)")
//[Link](":nth-child(even)")
.nodes();
[Link]((e) => {
[Link]([Link])})
</script></body></html>
Filtering the data:Output
Creating a server to upload your data
Typically with Apache or any other web server, data
directory is made.
In that the data, i.e. xml, csv, json, text files are put.
We here put in same directory as our scripts are
there.
If we put in the data directory of htdocs folder of
apache web server, we can access it as
[Link] or /data/[Link]
D3’s function for loading data
D3’s functions for Loading the data we have seen in for text,
csv, tsv, xml, json, html files.
Let’s see code for html files.
<head><script type="text/javascript"
src="[Link]
<body>
<script type="text/javascript">
[Link]("[Link]", function(data) {
[Link](data)});
</script>
D3’s function for loading html data
:output
Dealing with Asynchronous requests
<script>
Var popdata;
[Link]("[Link]", function (d) {
popdata=d;
});
[Link](popdata);
</script>

 If above script is there, result would be unexpected. [Link].


 It seems like pop Data should be the old, familiar array, when
[Link](data) was part of the callback function. But there’s a very
good reason why it isn’t.
 When you use [Link](), your script doesn’t wait for the callback
function to finish before it starts running the rest of the code. In
technical terms, D3 makes external requests asynchronously
Dealing with Asynchronous requests
<script>
var popdata;
[Link]("[Link]", function (d) {
popdata=d;
});
[Link](popdata);
</script>
 So for large data set—one that takes multiple seconds to load. You
don’t really want all of your code to be held up by that load time.
 Ideally, everything that doesn’t involve your data will run while your
data is being pulled in so that all of the non-data-driven stuff on
your page can initialize.
Dealing with Asynchronous requests
 Practically speaking, what this means is that everything you do with
external data has to happen inside the callback function.
 So, if you wanted to change the code above so it actually works, you
would need to do this:

<script>
var popdata;
[Link]("[Link]", function (d) {
popdata=d;
[Link](popdata);
});
</script>
Loading Large Data Sets
<script>
data = [Link]("[Link]", function(d) {
[Link](d); });
</script>

Loading Large Data Sets:Output


Load and format large dataset
<head><title>Large Data set load and format</title>
<script src="[Link]
</head>
<body>
<script type="text/javascript">
[Link]("[Link]").then(function(data) {
[Link](function(d) {
//format output as city: value,population: value,...
[Link] = +[Link];
d["land area"] = +d["land area"];
});
//printing first line only
[Link](data[0]);
});</script>
Load and format large dataset
Making Charts Interactive
and
Animated
What is a Data Join?

 In [Link], data joins are a core concept for dynamically creating,


updating, and removing DOM (Document Object Model)
elements (like HTML or SVG elements) based on data.
 It's a powerful mechanism for building interactive and data-
driven visualizations
 D3's data join establishes a correspondence between an array
of data and a selection of DOM elements.
 This binding allows D3 to efficiently manipulate the elements
based on the data, enabling dynamic and interactive
visualizations.
Why data joins are essential?
Data joins are crucial for:
 Efficiency:
They enable D3 to efficiently manage DOM updates, improving
performance.
 Dynamic Data Binding:
They allow visualizations to update automatically when the
data changes, making them interactive and responsive.
 Declarative Approach:
They support a declarative style of coding where you define
the relationship between your data and the visual output,
letting D3 handle the necessary DOM manipulations.
Key methods
 [Link](data, [key]):
This method joins data to selected elements.
The data parameter is an array of values (e.g., numbers or objects) that
you want to associate with the elements.
The optional key function helps D3 identify and track specific elements
even when the data order changes, explains D3 in Depth.
 [Link]():
This returns a selection containing placeholder nodes for each data item
that doesn't have a corresponding DOM element in the initial selection.
This is used to create new elements for new data points.
 [Link]():
This returns a selection containing DOM elements that no longer have a
corresponding data point after the data join. This allows you to remove
elements that are no longer needed.
[Link]([enter][,update][,exit]):
 This is a shorthand method introduced in D3 v5+ that combines
the enter, update, and exit operations in a more concise way.
 It can take optional functions for each phase to define how
elements are handled (e.g., creating new elements, updating
existing ones, or removing old ones)
Enter, update, exit pattern
This is a fundamental pattern in D3 that describes how
elements are managed in a data join:
 Enter: New data points are added to the visualization.
 Update: Existing data points that match existing elements
are updated.
 Exit: Elements that no longer have corresponding data
points are removed.
How Data Join Works?
 The primary purpose of the Data join is to map the elements of the
existing document with the given data set. It creates a virtual
representation of the document with respect to the given data set
and provides methods to work with the virtual representation.
 [10, 20, 30, 25, 15]
 Let us map it to the li element of the following document using the
selector's selectAll() method and data join's data() method.
 HTML
<ul id = "list">
<li><li>
<li></li>
</ul>
 [Link] code
[Link]("#list").selectAll("li").data([10, 20, 30, 25, 15]);
How Data Join Works?
 We can use all the selector's element modifying methods like attr(),
style(), text(), etc., for the first two li as shown below.
[Link]("#list").selectAll("li") .data([10, 20, 30, 25, 15])
.text(function(d) { return d; });
The function in the text() method is used to get the li elements
mapped data. Here, d represent 10 for first li element and 20 for
second li element.

 The next three elements can be mapped to any elements and it can be
done using the data join's enter() and selector's append() method.
• The enter() method gives access to the remaining data (which is not
mapped to the existing elements) and
• the append() method is used to create a new element from the
corresponding data.
How Data Join Works?
 The code to create new a li element is as follows −
[Link]("#list").selectAll("li")
.data([10, 20, 30, 25, 15])
.text(function(d) { return "This is pre-existing element and the value is "
+ d; })
.enter()
.append("li")
.text(function(d)
{ return "This is dynamically created element and the value is " + d;
});
How Data Join Works?
Data join provides another method called as the exit()
method to process the data items removed dynamically from the
data set
[Link]("li")
.data([10, 20, 30, 15])
.exit()
.remove()
Program
<html> .data([10, 20, 30, 25, 15])
<head> .text(function(d)
<script type = "text/javascript" src = { return "This is pre-existing element and
"[Link] the value is " + d; })
<style> .enter()
body { font-family: Arial; } .append("li")
</style> .text(function(d)
</head> { return "This is dynamically created
element and the value is " + d; });
<body>
function remove() {
<ul id = "list">
[Link]("li")
<li></li>
.data([10, 20, 30, 15])
<li></li>
.exit()
</ul>
.remove()
<input type = "button" name = "remove" value =
"Remove fourth value" }
onclick = "javascript:remove()" /> </script>
<script> </body>
[Link]("#list").selectAll("li") </html>
Output
Create SVG Elements using D3
 SVG provides different shapes like lines, rectangles, circles,
ellipses etc.
 Hence, designing visualizations with SVG gives you more
flexibility and power in what you can achieve.
 What is SVG?
SVG is an image that is text-based.
SVG is similar in structure to HTML
SVG sits in the DOM
SVG properties can be specified as attributes
SVG should have absolute positions relative to the origin (0, 0)
Line in SVG
<svg width="500" height="500">
<line x1="100" y1="50" x2="500" y2="50" stroke="black"/>
</svg>
 A line's attributes are:
 x1: This is the x-coordinate of the first point
 y1: This is the y-coordinate of the first point
 x2: This is the x-coordinate of the second point
 y2: This is the y-coordinate of the second point
Draw SVG Line with D3
<!doctype html> .attr("width", width)
<html> .attr("height", height);
<head> //Create line element inside SVG
<script
src="[Link] [Link]("line")
</script> .attr("x1", 100)
</head> .attr("x2", 500)
<body> .attr("y1", 50)
<script> .attr("y2", 50)
var width = 500; .attr("stroke", "black")
var height = 500; </script>
//Create SVG element </body>
var svg = [Link]("body") </html>
.append("svg")
SVG Rectangle
<!doctype html>
<html>
<head>
<script src="[Link]
</script>
</head>
<body>
<svg width="500" height="500">
<rect x="0" y="0" width="200" height="200"></rect>
</svg>
</body>
</html>
Draw SVG Rectangle with D3
<!doctype html> var svg = [Link]("body")
.append("svg")
<html>
.attr("width", width)
<head> .attr("height", height);
<script //Create and append rectangle
src="[Link] element
</script> [Link]("rect")
</head> .attr("x", 0)
.attr("y", 0)
<body> .attr("width", 200)
<script> .attr("height", 100)
var width = 500; </script>
var height = 500; </body
//Create SVG element </html>
SVG Circle
<!doctype html>
<html>
<body>
<svg width="500" height="500">
<circle cx="250" cy="50" r="50"/>
</svg>
</body>
</html>
 Circle attributes:
• cx: This is the x-coordinate of the center of the circle
• cy: This is the y-coordinate of the center of the circle
• r: This denotes the radius of the circle
Draw SVG Circle with D3
<!doctype html> .attr("height", height);
<html> //Append circle
<head> [Link]("circle")
.attr("cx", 250)
<script
src="[Link] .attr("cy", 50)
</script> .attr("r", 50)
</head> </script>
<body> </body>
<script> </html>
var width = 500;
var height = 500;
//Create SVG element
var svg = [Link]("body")
.append("svg")
.attr("width", width)
SVG Ellipse
<!doctype html>  ellipse's attributes are:
<html> • cx: This is the x-coordinate of
the center of the circle
<head>
• cy: This is the y-coordinate of
<script
the center of the circle
src="[Link]
• rx: This is the x radius of the
</script>
circle
</head>
• ry: This is the y radius of the
<body> circle
<svg width="500" height="500">

<ellipse cx="250" cy="25"


rx="100" ry="25"/>
</svg>
</body>
</html>
Draw SVG Ellipse with D3

<!doctype html> [Link]("ellipse")


.attr("cx", 250)
<html>
.attr("cy", 50)
<head>
.attr("rx", 150)
<script
src="[Link] .attr("ry", 50)
ript>
</script>
</head>
</body>
<body>
</html>
<script>
var width = 500;
var height = 500;
var svg = [Link]("body")
.append("svg")
.attr("width", width)
.attr("height", height);
Text

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


<text x="250" y="25">Your text here</text>
</svg>
Text on Ellipse
<!doctype html>
<html> .append("svg")
<head> .attr("width", width)
<script
src="[Link] .attr("height", height);
>
</ script> //Create group element
</head> var g = [Link]("g")
<body>
.attr("transform", function(d, i) {
<script>
var width = 500;
return "translate(0,0)";
var height = 500; });
//Create SVG element
var svg = [Link]("body")
Text on Ellipse
//Create and append ellipse element into group
var ellipse = [Link]("ellipse")
.attr("cx", 250)
.attr("cy", 50)
.attr("rx", 150)
.attr("ry", 50)
.append("text")
//Create and append text element into group
[Link]("text")
.attr("x", 150)
.attr("y", 50)
.attr("stroke", "#fff")
.text("This is an ellipse!");
</script>
</body>
</html>
Program on Interactive Buttons
<!DOCTYPE html> .attr("cx", 150)
<meta charset="utf-8"> .attr("cy", 100)
<body> .attr("r", 50)
<button id="changeColor">Change .attr("fill", "steelblue");
Color</button>
// Button click event
<svg width="300" [Link]("#changeColor")
height="200"></svg>
.on("click", () => {
<script
src="[Link] [Link]("circle")
</script> .attr("fill", "tomato");
<script> });
const svg = [Link]("svg"); </script>
// Draw a circle </body>
[Link]("circle")
Output
Small animated D3 data join with keys
<!DOCTYPE html> ];
<meta charset="utf-8"> function update(data) {
<body> const circles = [Link]("circle")
<svg width="500" height="150"> .data(data, d => [Link]); // KEY
FUNCTION
</svg>
<script
src="[Link] // EXIT
</script> [Link]()
<script> .transition().duration(500)
const svg = [Link]("svg"); .attr("r", 0)
let data = [ .remove();
{ id: "A", value: 20, x: 50 },
{ id: "B", value: 30, x: 150 },
{ id: "C", value: 25, x: 250 }
Small animated D3 data join with keys
// ENTER + UPDATE MERGED // Change data every 2 seconds
[Link]() setInterval(() => {
.append("circle") data = [Link](data); // shuffle
order
.attr("cx", d => d.x)
// Randomly change values and
.attr("cy", 75)
positions
.attr("r", 0) // start small
[Link]((d, i) => {
.style("fill", "steelblue")
[Link] = 10 + [Link]() * 30;
.merge(circles)
d.x = 50 + i * 100;
// merge enter + update
});
.transition().duration(1000)
update(data);
.attr("cx", d => d.x)
}, 2000);
.attr("r", d => [Link]);
</script>
}
// Initial render
update(data);
[Link] bar chart
<!DOCTYPE html> .attr("y", d => 100 - d)
<html> .attr("width", 20)
<body> .attr("height", d => d)
<svg width="200" .attr("fill", "orange");
height="100"></svg>
</script>
<script
</body>
src="[Link]
</html>
</script>
<script>
const data = [10, 30, 20];
[Link]("svg")
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (d,i) => i * 30)
[Link] bar chart with animation
<!DOCTYPE html> // start from bottom
<html> .attr("width", 20)
<body> .attr("height", 0)
<svg width="200" height="100"></svg> // start with height 0
<script .attr("fill", "orange")
src="[Link]
.transition() // <— animation starts here
</script>
.duration(800) // 0.8 seconds
<script>
.attr("y", d => 100 - d)
const data = [10, 30, 20];
.attr("height", d => d);
[Link]("svg")
</script>
.selectAll("rect")
</body>
.data(data)
</html>
.join("rect")
.attr("x", (d,i) => i * 30)
.attr("y", 100)
[Link] bar chart
<!doctype html> <svg className="chart" width="420"
<html> height="120">
<head> <g transform="translate(0,0)">
<script <rect width="50" height="19"></rect>
src="[Link] <text x="47" y="9.5"
dy=".35em">5</text></g>
</head>
<g transform="translate(0,20)">
<style>
<rect width="100" height="19"></rect>
svg rect {
<text x="97" y="9.5" dy=".35em">10</text>
fill: orange;
</g>
}
<g transform="translate(0,40)">
svg text {
<rect width="120" height="19"></rect>
fill:white;
<text x="117" y="9.5" dy=".35em">12</text>
font: 10px sans-serif;
</g>
text-anchor: end;
</svg>
}
</body>
</style>
</html>
<body>
Circle
<!DOCTYPE html> .attr("fill", "steelblue");
<html> </script>
<body> </body>
<svg width="200" height="100"></svg> </html>
<script src="[Link]
</script>
<script>
const data = [10, 20, 15]; // circle radii
[Link]("svg")
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", (d,i) => 40 + i * 60) // X position
.attr("cy", 50) // Y position
.attr("r", d => d) // radius from data
Pie chart
<!DOCTYPE html> .innerRadius(0) // pie (0) or donut (>0)
<html> .outerRadius(80); // size of pie
<body> const svg = [Link]("svg")
<svg width="200" height="200"></svg> .append("g")
<script .attr("transform",
src="[Link] "translate(100,100)"); // center the pie
</script> [Link]("path")
<script> .data(pie)
const data = [10, 20, 30]; .join("path")
// pie slice values .attr("d", arc)
const colors = .attr("fill", (d,i) => colors(i));
[Link](["orange", "skyblue",
</script>
"lightgreen"]);
</body>
const pie = [Link]()(data);
</html>
// compute angles
const arc = [Link]()
Animated pie chart
<!DOCTYPE html> .data(pie)
<html> .join("path")
<body> .attr("fill", (d,i) => colors(i))
<svg width="200" height="200"></svg> .transition()
<script .duration(1000)
src="[Link]
.attrTween("d", function(d) {
<script>
const i = [Link](
const data = [10, 20, 30]; // pie slice values
{ startAngle: 0, endAngle: 0 },
const colors = [Link](["orange",
"skyblue", "lightgreen"]); // start collapsed

const pie = [Link]()(data); d // final slice


);
const arc = [Link]()
.innerRadius(0) return t => arc(i(t));

.outerRadius(80); });

const svg = [Link]("svg") </script>

.append("g") </body>

.attr("transform", "translate(100,100)"); // </html>


center the pie
[Link]("path")
Line chart
<!DOCTYPE html> .attr("stroke", "blue")
<html> .attr("stroke-width", 2);
<body> </script>
<svg width="200" height="100"></svg> </body>
<script </html>
src="[Link]
</script>
<script>
const points = [ [0,80], [50,40],
[100,60], [150,20], [200,50] ];
const line = [Link]();
[Link]("svg")
.append("path")
.attr("d", line(points))
.attr("fill", "none")
Animated Line chart
<!DOCTYPE html> .attr("stroke", "blue")
<html> .attr("stroke-width", 2);
<body> const totalLength =
[Link]().getTotalLength();
<svg width="200"
height="100"></svg> path
<script .attr("stroke-dasharray", totalLength
src="[Link] + " " + totalLength)
</script> .attr("stroke-dashoffset",
totalLength)
<script>
.transition()
const points = [ [0,80], [50,40],
[100,60], [150,20], [200,50] ]; .duration(4000) // 4 second
const line = [Link](); .ease([Link])
const path = [Link]("svg") .attr("stroke-dashoffset", 0);
.append("path") </script>
.attr("d", line(points)) </body>
.attr("fill", "none") </html>
Bubble Chart
 A bubble chart in [Link] is essentially a scatter plot where
each data point is represented by a circle, and the size of the
circle (radius) encodes an additional quantitative variable.
 You can make two main types of bubble charts in D3:
1. Simple scatter-like bubble chart – X/Y positions from data,
radius from a variable.
2. Packed bubble chart – circles packed together using D3’s
pack() layout.
Scatter-like Bubble Chart
<!DOCTYPE html> ];
<meta charset="utf-8"> [Link]("circle")
<body> .data(data)
<svg width="500" height="300"></svg> .join("circle")
<script .attr("cx", d => d.x)
src="[Link]
.attr("cy", d => d.y)
</script>
.attr("r", d => d.r)
<script>
.attr("fill", "steelblue")
const svg = [Link]("svg");
.attr("opacity", 0.7);
const data = [
</script>
{x: 50, y: 150, r: 20},
</body>
{x: 150, y: 100, r: 30},
{x: 250, y: 200, r: 25},
{x: 350, y: 120, r: 40}
Packed bubble chart
<!DOCTYPE html> {name: "B", value: 40},
<meta charset="utf-8"> {name: "C", value: 10},
<body> {name: "D", value: 30}
<svg width="500" ];
height="300"></svg>
// Create packed layout
<script const root = [Link]()
src="[Link]
/script> .size([width, height])
<script> .padding(5)(
const svg = [Link]("svg"), [Link]({children: data})
width = +[Link]("width"), .sum(d => [Link])
height = +[Link]("height"); );

const data = [
{name: "A", value: 20},
Packed bubble chart
// Draw bubbles .attr("text-anchor", "middle")
[Link]("circle") .attr("dy", ".3em")
.data([Link]()) .text(d => [Link]);
.join("circle") </script>
.attr("cx", d => d.x) </body>
.attr("cy", d => d.y)
.attr("r", d => d.r)
.attr("fill", "orange")
.attr("opacity", 0.8);
// Add labels
[Link]("text")
.data([Link]())
.join("text")
.attr("x", d => d.x)
.attr("y", d => d.y)
Animated Bubble chart
<!DOCTYPE html> {name: "B", value: 40},
<meta charset="utf-8"> {name: "C", value: 10},
<body> {name: "D", value: 30}
<svg width="500" height="300"></svg> ];
<script
src="[Link]
// Create packed layout
pt>
const root = [Link]()
<script>
.size([width, height])
const svg = [Link]("svg"),
.padding(5)(
width = +[Link]("width"),
[Link]({children: data})
height = +[Link]("height");
.sum(d => [Link])
);
const data = [
{name: "A", value: 20},
Animated Bubble chart
// Draw animated bubbles .data([Link]())
[Link]("circle") .join("text")
.data([Link]()) .attr("x", d => d.x)
.join("circle") .attr("y", d => d.y)
.attr("cx", d => d.x) .attr("text-anchor", "middle")
.attr("cy", d => d.y) .attr("dy", ".3em")
.attr("r", 0) // start small .text(d => [Link])
.attr("fill", "orange") .style("opacity", 0)
.attr("opacity", 0.8) .transition()
.transition() .delay(500)
.duration(1000) // 1 second .duration(500)
animation
.style("opacity", 1);
.attr("r", d => d.r);
</script>
</body>
// Add labels
[Link]("text")
Questions:
 What is the purpose of [Link]() and [Link]()? Explain with examples.
 Explain D3’s selection mechanism and how it enables data-driven DOM
manipulation. Include examples.
 How does the enter-update-exit pattern work with D3 selections?
 Explain the concept of a Data Join in [Link]. Why is it considered essential for
dynamic data visualization? Describe how it works using the enter-update-exit
pattern, with a code example.
 Explain applications of [Link] library
 Explain [Link] library
 Describe the process of making selections and changing their attributes in [Link]
with suitable code snippets.
 Discuss different data formats supported by [Link] (CSV, JSON, TSV). Which one
would you prefer for hierarchical data and why?
 Explain how external data can be loaded and filtered in [Link]. Provide a small
example.
 How can you create a simple server to upload and serve data for use with [Link]?
Illustrate with steps.
Questions:
 Explain asynchronous requests in D3 with an example. How does D3 handle
callback functions or promises?
 Discuss techniques for loading and formatting large data sets in [Link]. Provide
an example scenario.
 What do you mean by asynchronous requests in D3? Why are they important?
 Explain the role of [Link]() in loading external data.
 Briefly describe how D3 handles JSON data loading.
 Explain how D3 allows updating existing charts with new data. How does the
use of keys improve this process?
 Discuss how interactive buttons can be used to update and animate charts in
D3. Provide an example scenario.
 Write a short note on changing selection attributes in [Link].

You might also like