Full Download Data Visualization with Python and JavaScript 2nd Edition Kyran Dale PDF DOCX
Full Download Data Visualization with Python and JavaScript 2nd Edition Kyran Dale PDF DOCX
com
https://ebookmeta.com/product/data-visualization-with-
python-and-javascript-2nd-edition-kyran-dale/
OR CLICK HERE
DOWLOAD NOW
https://ebookmeta.com/product/data-visualization-with-python-and-
javascript-2nd-edition-kyran-dale-2/
ebookmeta.com
https://ebookmeta.com/product/data-visualization-with-python-and-
javascript-2nd-edition-third-early-release-kyran-dale/
ebookmeta.com
https://ebookmeta.com/product/data-visualization-with-python-and-
javascript-2nd-edition-seventh-early-release-kyran-dale/
ebookmeta.com
https://ebookmeta.com/product/theoretical-models-and-processes-of-
literacy-seventh-edition-donna-e-alvermann/
ebookmeta.com
Practical Petroleum Geochemistry for Exploration and
Production 2nd Edition Harry Dembicki
https://ebookmeta.com/product/practical-petroleum-geochemistry-for-
exploration-and-production-2nd-edition-harry-dembicki/
ebookmeta.com
https://ebookmeta.com/product/recurrent-spontaneous-miscarriages-3rd-
edition-pankaj-desai/
ebookmeta.com
https://ebookmeta.com/product/property-investing-essentials-for-
dummies-australian-edition-nicola-mcdougall/
ebookmeta.com
https://ebookmeta.com/product/bruce-lee-artist-of-life-inspiration-
and-insights-from-the-world-s-greatest-martial-artist-bruce-lee-john-
little/
ebookmeta.com
https://ebookmeta.com/product/indirect-judicial-review-in-
administrative-law-legality-vs-legal-certainty-in-europe-1st-edition-
mariolina-eliantonio/
ebookmeta.com
iPhone For Dummies Updated for iPhone 12 models and iOS 14
14th Edition Edward C. Baig
https://ebookmeta.com/product/iphone-for-dummies-updated-for-
iphone-12-models-and-ios-14-14th-edition-edward-c-baig/
ebookmeta.com
Data Visualization with Python
and JavaScript
Scrape, Clean, Explore, and Transform Your Data
SECOND EDITION
With Early Release ebooks, you get books in their earliest form—
the author’s raw and unedited content as they write—so you can
take advantage of these technologies long before the official
release of these titles.
Kyran Dale
Data Visualization with Python and JavaScript
by Kyran Dale
Copyright © 2023 Kyran Dale Limited. All rights reserved.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North,
Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales
promotional use. Online editions are also available for most titles
(http://oreilly.com). For more information, contact our
corporate/institutional sales department: 800-998-9938 or
[email protected].
Probably the most ambitious aspect of this book is that it deals with
two programming languages. Moreover, it only requires that you are
competent in one of these languages. This is only possible because
Python and JavaScript (JS) are fairly simple languages with much in
common. The aim of this chapter is to draw out those commonalities
and use them to make a learning bridge between the two languages
such that core skills acquired in one can easily be applied to the
other.
After showing the key similarities and differences between the two
languages, I’ll show how to set up a learning environment for Python
and JS. The bulk of the chapter will then deal with core syntactical
and conceptual differences, followed by a selection of patterns and
idioms that I use often while doing data visualization work.
The differences here emphasize the need for this book to be bi-
lingual. JavaScript’s monopoly of browser dataviz needs the
complement of a conventional data-processing stack. And Python has
the best there is.
Python
By far, the best command-line Python interpreter is IPython, which
comes in three shades: the basic terminal version, an enhanced
graphical version, and a browser-based notebook. Since version 4.0
the latter two have been spun out into project Jupyter. The Jupyter
notebook is a rather brilliant and fairly recent innovation, providing a
browser-based interactive computational environment. There are pros
and cons to the different versions. The command line is fastest to
scratch a problematic itch but lacks some bells and whistles,
particularly embedded plotting courtesy of Matplotlib and friends. The
makes it suboptimal for Pandas-based data-processing and data
visualization work. Of the other two, both are better for multiline
coding (e.g., trying out functions) than the basic interpreter, but I
find the graphical Qt console more intuitive, having a familiar
command line rather than executable cells.4 The great boon of the
Notebook is session persistence and the possibility of web access.5
The ease with which one can share programming sessions, complete
with embedded data visualizations, makes the notebook a fantastic
teaching tool as well as a great way to recover programming context.
That’s why the Python chapters of this book have accompanying
Jupyter notebooks.
You can start an ipython session at the command-line like this:
$ ipython
$ jupyter notebook
[I 15:27:44.553 NotebookApp] Serving notebooks from local
directory:
...
[I 15:27:44.553 NotebookApp] http://localhost:8888/?token=5e09...
JavaScript
There are lots of options for trying out JavaScript code without
starting a server, though the latter isn’t that difficult. Because the
JavaScript interpreter comes embedded in all modern web browsers,
there are a number of sites that let you try out bits of JavaScript
along with HTML and CSS and see the results. Codepen is a good
option. These sites are great for sharing code and trying out
snippets, and usually allow you to add libraries such as D3.js with a
few mouse-clicks.
If you want to try out code one-liners or quiz the state of live code,
browser-based consoles are your best bet. With Chrome, you can
access the console with the key combo Ctrl-Shift-J. As well as trying
little JS snippets, the console allows you to drill down into any objects
in scope, revealing their methods and properties. This is a great way
to quiz the state of a live object and search for bugs.
One disadvantage of using online JavaScript editors is losing the
power of your favorite editing environment, with linting, familiar
keyboard shortcuts, and the like (see Chapter 3). Online editors tend
to be rudimentary, to say the least. If you anticipate an extensive
JavaScript session and want to use your favorite editor, the best bet
is to run a local server.
First, create a project directory—called sandpit, for example—and add
a minimal HTML file that includes a JS script:
sandpit
├── index.xhtml
└── script.js
The index.xhtml file need only be a few lines long, with an optional
div placeholder on which to start building your visualization or just
trying out a little DOM manipulation.
<div id='viz'></div>
// script.js
sum += d;
});
Now that we’ve established how to run the demo code, let’s start
building a bridge between Python and JavaScript. First, we’ll cover
the basic differences in syntax. As you’ll see, they’re fairly minor and
easily absorbed.
'use strict';
// ...
}(window.foo = window.foo || {});
FOO_CONST = 10
class FooBar(object): # ...
def foo_bar():
<!DOCTYPE html>
<meta charset="utf-8">
...
<script src="http://d3js.org/d3.v7.min.js"></script>
You can include the script anywhere in your HTML file, but it’s best
practice to add scripts after the body (div tags, etc.) section.7 Note
that the order of the <script> tags is important. If a script is
dependent on a module (e.g., it uses the D3 library), its <script> tag
must be placed after that of the module. In other words, big library
scripts, such as jQuery and D3, will be included first.
Python comes with “batteries included,” a comprehensive set of
libraries covering everything from extended data containers
(collections) to working with the family of CSV files (csv). If you
want to use one of these, just import it using the import keyword:
In [2]: sys.platform
Out[2]: 'linux'
If you don’t want to import the whole library or want to use an alias,
you can use the as and from keywords instead:
import pandas as pd
from csv import DictWriter, DictReader
from numpy import *
df = pd.read_json('data.json')
reader = DictReader('data.csv')
This imports all the variables from the module into the
current namespace and is almost always a bad idea. One of
the variables could mask an existing one, and it goes
against the Python best practice of explicit being better than
implicit. One exception to this rule is if you are using the
Python interpreter interactively. In this limited context, it
may make sense to import all functions from a library to cut
down on key presses; for example, importing all the math
functions (from math import *) if doing some Python math
hacking.
...
└── io
├── __init__.py
└── api.py
...
└── tests
└── __init__.py
└── test_data.py
└── test_excel.py
...
...
You can access packages on sys.path from the root directory (that’s
mypackage in Example 1-1) using dot notation. A special case of
import is intrapackage references. The test_excel.py submodule in
Example 1-1 can import submodules from the mypackage package
both absolutely and relatively:
// ...
}(window.nbviz = window.nbviz || {}));
# In Python 2*
print 'Hello World!'
# In Python 3+
print('Hello World!')
You can use Python 3’s print function in Python 2 by importing it from
the __future__ module:
console.log('Hello World!);
# B
def process_student_data(data, pass_threshold=60,
merit_threshold=75):
""" Perform some basic stats on some student data. """
# C
for sdata in data:
av = sum(sdata['scores'])/float(len(sdata['scores']))
sdata['average'] = av
if av > merit_threshold:
sdata['assessment'] = 'passed with merit'
elif av > pass_threshold:
sdata['assessment'] = 'passed'
else:
sdata['assessment'] = 'failed'
# D
print("%s's (id: %d) final assessment is: %s"%(
sdata['name'], sdata['id'], sdata['assessment'].upper()))
# E
if __name__ == '__main__':
process_student_data(student_data)
// B
function processStudentData(data, passThreshold, meritThreshold){
passThreshold = typeof passThreshold !== 'undefined'?\
passThreshold: 60;
meritThreshold = typeof meritThreshold !== 'undefined'?\
meritThreshold: 75;
// C
data.forEach(function(sdata){
var av = sdata.scores.reduce(function(prev, current){
return prev+current;
},0) / sdata.scores.length;
sdata.average = av;
sdata.assessment = 'passed';
}
else{
sdata.assessment = 'failed';
}
// D
console.log(sdata.name + "'s (id: " + sdata.id +
}
// E
processStudentData(studentData);
String Construction
Section D in Examples 1-3 and 1-4 show the standard way to print
output to the console or terminal. JavaScript has no print statement
but will log to the browser’s console through the console object.
These days, I rarely use Python’s print statement, opting for the
much more powerful and flexible logging module, which is
demonstrated in the following code block. It takes a little more effort
to use, but it is worth it. Logging gives you the flexibility to direct
output to a file and/or the screen, adjusting the logging level to
prioritize certain information, and a whole load of other useful things.
Check out the details here.
import logging
logger = logging.getLogger(__name__)
//...
logger.debug('Some useful debugging output')
logger.info('Some general information')
// IN INITIAL MODULE
logging.basicConfig(level=logging.DEBUG)
return x * 2;
}
def doubler(x):
"""This function returns double its input."""
return 2 * x
def sanitize_string(s):
"""This function replaces any string spaces
with '-' after stripping any whitespace
"""
return s.strip().replace(' ', '-')
TIP
JavaScript has variable hoisting, which means variables declared with var are
processed before any other code. This means declaring them anywhere in the
function is equivalent to declaring them at the top. This can result in weird errors
and confusion. Explicitly placing vars at the top avoids this but it’s better to use
the modern let and have scoped declarations.
Python has three numeric types: the 32-bit int,to which the student
scores are cast, a float equivalent (IEE 754) to JS’s number, and a
long for arbitrary precision integer arithmetic. This means that Python
can represent any integer, whereas JavaScript is more limited.16
Python’s casting changes type:
The nice thing about Python and JavaScript numbers is that they are
easy to work with and usually do what you want. If you need
something more efficient, Python has the NumPy library, which allows
fine-grained control of your numeric types (you’ll learn more about
NumPy in Chapter 6). In JavaScript, aside from some cutting-edge
projects, you’re pretty much stuck with 64-bit floats.
Booleans
Python differs from the JavaScript and the C class languages in using
named boolean operators. Other than that, they work pretty much as
expected. This table gives a comparison:
Python bool True False not and or
rocket_launch = True
(rocket_launch == True and 'All OK') or 'We have a problem!'
Out:
'All OK'
rocket_launch = False
(rocket_launch == True and 'All OK') or 'We have a problem!'
Out:
'We have a problem!'
# Python
d = {'name': 'Groucho', 'occupation': 'Ruler of Freedonia'}
l = ['Harpo', 'Groucho', 99]
t = ('an', 'immutable', 'container')
// JavaScript
d = {'name': 'Groucho', 'occupation': 'Ruler of Freedonia'}
l = ['Harpo', 'Groucho', 99]
It’s good to be aware that although they can be used like Python
dictionaries, JavaScript objects are much more than just containers
(aside from primitives like strings and numbers, pretty much
everything in JavaScript is an object).17 But in most dataviz examples
you see, they are used very much like Python dicts.
Table 1-2 converts basic list operations.
a.length len(l)
a.push(item) l.append(item)
a.pop() l.pop()
a.shift() l.pop(0)
Functions
Section B of Examples 1-3 and 1-4 shows a function declaration.
Python uses def to indicate a function:
...
Both have a list of parameters. With JS, the function code block is
indicated by the curly brackets { … }; with Python, the code block is
defined by a colon and indentation.
JS has an alternative way of defining a function called the function
expression, which you may see in examples: