39,59 €
Master the art of building responsive visualizations on the Web
Web developers and data science professionals who want to make their visualizations work for smaller screen sizes. Some basic knowledge of JavaScript and Data visualization is expected.
Using D3.js and Responsive Design principles, you will not just be able to implement visualizations that look and feel awesome across all devices and screen resolutions, but you will also boost your productivity and reduce development time by making use of Bootstrap—the most popular framework for developing responsive web applications.
This book teaches the basics of scalable vector graphics (SVG), D3.js, and Bootstrap while focusing on Responsive Design as well as mobile-first visualizations; the reader will start by discovering Bootstrap and how it can be used for creating responsive applications, and then implement a basic bar chart in D3.js. You will learn about loading, parsing, and filtering data in JavaScript and then dive into creating a responsive visualization by using Media Queries, responsive interactions for Mobile and Desktop devices, and transitions to bring the visualization to life. In the following chapters, we build a fully responsive interactive map to display geographic data using GeoJSON and set up integration testing with Protractor to test the application across real devices using a mobile API gateway such as AWS Device Farm.
You will finish the journey by discovering the caveats of mobile-first applications and learn how to master cross-browser complications.
As the world shifts to mobile devices for consuming data on the Web, developers are faced with the unique challenge of making data visualizations work for their smaller screens. The growth of responsive web design enabled developers to adopt page layouts and media for smaller screens, but there is still little information available on how to adapt data visualizations for the smaller screens. This book fills this important gap and shows how responsive web design principles can be extended to create visualizations that work well regardless of the screen size, thereby allowing developers to build user-friendly visualizations that work well on all devices. In addition to covering some of the popular techniques and design patterns for building responsive visualizations, the book also shows readers how to implement these techniques with the help of some popular tools and libraries.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 288
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2016
Production reference: 1180316
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-378-1
www.packtpub.com
Author
Christoph Körner
Reviewer
Sébastien Fragnaud
Commissioning Editor
Wilson D'souza
Acquisition Editor
Reshma Raman
Content Development Editor
Sachin Karnani
Technical Editor
Gebin George
Copy Editor
Yesha Gangani
Project Coordinator
Nikhil Nair
Proofreader
Safis Editing
Indexer
Monica Ajmera Mehta
Graphics
Disha Haria
Production Coordinator
Nilesh Mohite
Cover Work
Nilesh Mohite
Christoph Körner, CTO and lead developer at GESIM, a start-up company, is a passionate software engineer, web enthusiast, and an active member of the JavaScript community with more than 5 years of experience in developing customer-oriented web applications. He is the author of Data Visualizations with D3 and AngularJS and is currently pursuing his master's degree in Visual Computing at Vienna Institute of Technology.
I want to thank my close friends, Firat Özdemir and Vidor Kanalas, for their continuous support and help, as well as my boss and colleague, Dietmar Wiegand, for supporting all my ideas and dreams. I also want to thank my girlfriend, Laura Andrea Rojas Padilla, who has always inspired, motivated, and supported me, as well as the whole team at Pack Publishing for believing in me and supervising me during the last 6 months.
Sébastien Fragnaud is a frontend engineer who works at Metamarkets. He creates beautiful UIs out of beautiful mockups. Before this, he worked for several different companies, but his focus was always the same: presenting data in a meaningful manner.
Deeply fond of reusable code, he's the author of n3-charts, a JavaScript library that provides an easy way to manipulate charts in AngularJS applications.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Data visualizations are the best way to understand complex information and data. The human brain perceives visual information easily; it can make connections and is able to understand the complete process easier than without visualizations.
I am always delighted with the positive feedback from users whenever they understand a complex system easily by looking at a data visualization, instead of going through explanatory text and raw data. With the power of the Web and modern browsers, I can share these visualizations with everyone and make them interactive and animated.
To power cross-browser interactive visualization, I didn't want any compromise with regards to performance, debugging, quality, and interactivity, which led me to SVG. After deciding for SVG, I looked for a framework for SVG transformations giving raw access to all its underlying standards while also providing a rich set of visualization features - the D3.js library provides all of these.
D3.js is a visualization toolkit that facilitates the generation and manipulation of web-based vector graphics and provides full access to underlying SVG standards. Moreover, animations and interactive visualizations change the way users perceive web applications, and D3.js offers everything you need to make a visualization interactive out of the box.
While this has been working for the last few years, I realized that users are increasingly accessing visualizations with their mobile devices, though mostly through smartphone and tables. On most tablets, visualizations looked good, though interactions did not work anymore. Smartphone users experienced this as well when they tried to zoom into a browser but it somehow interfered with the zoom of the visualization and randomly toggled interactive features instead. For me, this was the sign I needed to fix the problem.
With the rise of responsive web design, there were already plenty of ideas for creating cross-browser and cross-platform applications that adapt to a user's device, screen size, and resolution. Apart from this, modern browsers already provide solid CSS and JavaScript functionality to implement responsive designs for all kinds of web applications.
The only logical step for me was to combine rich tools in order to create responsive applications and introduce the same ideas into data visualizations. I want my visualizations to adapt to the user's device, screen size, and resolution while providing cross-platform interactivity for mouse and touch gestures. In this book, I will share my knowledge, experience, and best practices on responsive data visualizations with you.
Chapter 1, Getting Started with Responsive Design, Bootstrap, and D3.js, gets you on track with today's concepts, technologies, and frameworks to create responsive applications.
Chapter 2, Creating a Bar Chart Using D3.js and SVG, helps you get started with D3.js and its concepts. You will learn how to draw points, shapes, and simple bar charts by the end of this chapter.
Chapter 3, Loading, Filtering, and Grouping Data, guides you so that you can get the maximum information out of real-world data.
Chapter 4, Making the Chart Responsive Using Bootstrap and Media Queries, goes through all of the steps needed to make visualizations responsive and adapt them to user devices.
Chapter 5, Building Responsive Interactions, teaches you to add truly responsive interactions to your visualization, which also makes these great to use on user devices.
Chapter 6, Designing Transitions and Animations, teaches you to make a visualization appealing to look at by adding gorgeous transitions or custom animations.
Chapter 7, Creating Maps and Cartographic Visualizations Using GeoJSON, helps you get started with geographic data processing and then visualize this data in cartographic visualizations.
Chapter 8, Testing Responsive Visualizations, shows you how to test responsive visualizations both manually and in an automated manner, and covers both unit and end-to-end testing.
Chapter 9, Solving Cross-Browser Issues, helps you avoid the most common pitfalls when dealing with cross-browser compatibility issues for responsive visualizations.
The first thing you need to get started with is a web browser and text editor, such as Sublime Text or Atom. Then, you need to install node.js (http://nodejs.org/)—which already includes the npm package manager—and the bower package manager (http://bower.io/). I will walk you through the installation of the required packages in the corresponding chapters.
For examples that require you to load data from your local hard drive, I would recommend that you install the http-server module (https://www.npmjs.com/package/http-server) to run all the examples from a local web server. An Internet connection is only required to install tools and libraries but not to run the examples.
This book is intended for data scientists, developers, and motivated beginners to implement custom responsive data visualizations using vector graphics. Whether you already know a bit about SVG and vector graphics in a browser or you have never used any visualization library before, you will be able to master the data-driven techniques of D3. In either case, this book will get you up and running as quickly as possible and also challenges you if you have already worked with D3.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/LearningResponsiveDataVisualization_ColoredImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
The best way to understand data is to visualize it and explore it using an interactive visualization. In this book, we are going to build such an interactive visualization (actually many of them) using the latest techniques and web technologies. To make the information accessible across all devices, we are going to make the visualizations responsive. However, before we can start, we need to understand what this actually means. We also want to reuse some existing frameworks to not just do a great job but also work in an efficient way.
This chapter serves as an introduction to the methods, technologies, and frameworks that we will use throughout the book, and it will help you understand why we are using them to create data visualizations and how they work together.
In this chapter you will learn the following:
First, you will learn about Responsive Design and how it can be used to design a visualization for various screen sizes and resolutions. Then, we will discuss the importance of some key technologies such as CSS3 (especially Media Queries) and HTML5 (especially the viewport meta tag).
In the following chapter, we will get acquainted to the popular CSS and HTML framework called Bootstrap. Don't worry if you have never heard about it; it helps us to build the application on the existing and well-tested components, such as grids and LESS Media Queries.
In the last section of this chapter, you will learn about Scalable Vector Graphics (SVG) in the browser; and you will understand why and when it is great to use vector graphics for visualizations. Then, we will see a brief introduction to D3.js, which is a versatile JavaScript library for data transformations and graphics generation. At the end of this chapter, you will understand why SVG is a great choice for designing interactive responsive visualizations for the web.
Responsive Design is a method for designing applications that can adapt their appearance and behavior to the user's device. It makes the application look and feel good across all different devices, and most often, it makes them usable on all devices.
An important paradigm in Responsive Design is to use relative dimensions instead of fixed widths, heights, margins, paddings, and font sizes throughout all the application to adapt the design to the various types of devices.
For web browsers, Responsive Design was enabled through CSS3 and HTML5 features, such as Media Queries, the viewport meta tag, and new dimension units.
Media Queries were introduced in CSS3 as a more flexible extension of Media Types. They allow the developer to apply conditional CSS styles only when a statement (a so-called query) matches a certain CSS property (so-called Media Features) and a Media Type. A typical Media Query has the following structure:
Here is a small selection of properties that can be used as Media Features:
A complete list of Media Features and Types can be found on MDN at https://developer.mozilla.org/de/docs/Web/CSS/Media_Queries/Using_media_queries.
In Responsive Design, we are mostly interested in querying the min-width or max-width property to apply different styles to devices that have different widths.
Let's see an example where we can apply a different background color depending on the minimal width of the browser window:
In the preceding example, all the div elements in the page have the background color red as long as the browser window's width is larger or equal to, 992 px (see the following figure):
Browser window width larger than 992px
Once the window width is smaller than 992 px, the background color of the div elements jumps to blue (see the following figure):
Browser window with width smaller than 992px
As we can see in the following figure, Media Queries are supported across all major browsers and Internet Explorer starting from version 9:
Cross-browser compatibility Media Queries from http://caniuse.com/#feat=css-mediaqueries
In Responsive Design, we call a state when a certain layout and Media Query is active, and we call a breakpoint the transition from one state to another.
Let's look at an example. First, we define some screen dimensions for the following devices:
Create a CSS snippet using Media Queries for these device dimensions:
In the preceding code, we defined four states with three breakpoints between these states where each state corresponds to a typical screen dimension and device type.
We can also see these breakpoints by reducing the size of a browser window while looking at a responsive web page; we observe how the design breaks at a certain width of the browser window. In the following figure, the breakpoint is visualized as a dashed line, showing the moment when one state breaks into a new one:
Breakpoint in Responsive Design
We can observe the same effect when we look at the Google Plus web page in the following figure. In the first two figures, the size of browser window changes, but the three-column layout stays the same. In the third image, the design breaks into a new layout with only two columns:
Breakpoints of the Google Plus page
Across mobile and desktop devices, there exists a vast variety of different pixel densities and screen resolutions. Displays with much higher resolution would render pages much smaller than displays with a lower resolution; this immediately leads to readability problems. To prevent this effect and fit bigger pages into smaller screens, a virtual window—the so-called viewport (the visible area of a web page)—was introduced. This allowed websites to render in the correct pixel resolution and scale to the full device width for maximal accessibility; however, developers had no control over this device-specific setting. Later, in HTML5, the viewportmeta tag was introduced in order to give developers full control over these viewport settings.
Today, a mobile-optimized application usually defines the following viewport tag in the head section of the web page to render the website normally and scale the content to the width of the device:
More information about all the valid viewport options can be found on MDN at https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag.
When dealing with Responsive Design, it is always a good idea to use relative units to describe the element's dimensions based on its parent element. Thus, when the parent container changes the size, all children elements adapt their sizes accordingly.
The most popular unit for relative dimensions is %, which defines the dimension based on a certain percent of the next absolute positioned parent element.
However, there are more useful units to describe relative dimensions; for example, the following two are based on the font-size:
These units have a big advantage; they are affected by the changes of the font-size setting in the browser. A simple example can be the adaption of the paddings when the user increases the font size of the browser.
A short summary and explanation of all different CSS units can be found on MDN at https://developer.mozilla.org/de/docs/Web/CSS/length.
Responsive applications should look and feel great (or work at all) on a huge number of devices with a huge number of different screen sizes and resolutions; they usually run on mobile devices as well as big TV screens. Thus, in the beginning of a project, every developer has to choose an approach to design the responsive application to master this transition; in general, we distinguish between the following methods:
In the desktop first method, we design for desktop devices and mouse input first, then we adjust and scale the design down for mobile devices and touch interactions. This often results in a web application with a reduced functionality for mobile devices due to a much smaller screen dimension and the lack of touch support.
In the mobile first method, we design for mobile devices and touch interactions first, and then we adjust and scale the design up for bigger devices and mouse interactions. This approach makes sure that mobile devices support a complete set of features, which can even be used on desktop clients.
Both methods are equally correct, accepted, and popular nowadays. The only exception is that mobile first became a buzzword due to an increase of mobile devices accessing the web during the previous years. Throughout the book, we will choose a mobile first approach and design for mobile devices and touch support. However, we will, of course, extend the visualizations to support mouse input and bigger screens. That's what the responsive design is all about.
If we want to create responsive mobile first web applications, we usually don't want to start from zero and re-implement common patterns and components; we would rather want to reuse some well-tested, existing components.
Bootstrap is a very popular HTML and CSS framework built by former Twitter employees for easy, fast, and modern frontend development; it provides loads of responsive CSS and LESS layouts as well as a huge collection of HTML and JavaScript components. Thanks to its MIT license, it can be used in open source and commercial software.
The current stable version 3.3.5 includes LESS styling with these features:
A complete list of features can be found on the Bootstrap website at http://getbootstrap.com/.
The new version 4 (which is currently in the alpha stage) will be shipped with SASS layouts and loads of other great features and improvements:
There also exists an official fork for the SASS precompiler on GitHub at https://github.com/twbs/bootstrap-sass.
A complete list of new features can be found on the Bootstrap blog at http://blog.getbootstrap.com/2015/08/19/bootstrap-4-alpha/.
Throughout this book, we will use Bootstrap 3.3.5 version (with LESS) for all the examples and explanations if they are not stated differently. We will also give some hints about the latest version where it is appropriate.
Make sure you have the Bower package manager installed; this can be done by running the following command from the terminal:
More information about the Bower package manager can be found on its website at http://bower.io/.
Throughout this book, we will make use of only the CSS components of Bootstrap and thus we only need to include the bootstrap.css file to our project. There are multiple ways of doing so:
I strongly recommend using the bower package manager to manage your frontend dependencies (or similar ones, such as npm or component). However, in the examples of this book, we will link Bootstrap directly from MaxCDN for simplicity reasons; therefore, all examples in the source of the book require an active Internet connection.
The ultimate resource for Bootstrap is the documentation that can be found at http://getbootstrap.com/getting-started/. Here, you will also find examples and templates using the Bootstrap framework.
For more detailed information and examples, I recommend reading the Unraveling Bootstrap 3.3 book by Istvan Novak.
A popular component to organize elements in an application or visualization is a grid layout. For responsive design in particular, we are mostly interested in grid layouts that adapt their columns to the screen resolution of the client. In the following figure, there's an example of a responsive grid layout with three columns per row on a desktop device and one column per row on a mobile device:
Simple Responsive grid, left: desktop, right: mobile
We then distinguish two different types of responsive grids that adapt the number of columns to the screen resolution of the client:
Grid types—left: grid with fixed width, right: fluid grid
It's actually quite simple to build a grid system yourself; let's first take a look at how to create a fluid grid layout, and afterwards, we will better understand how we can use Bootstrap components to get things done quickly and properly.
If we think about a grid as a (flexible) table layout, we need two basic components: rows and columns. A popular approach is to use the 12-column grid where we divide the width of a row into 12 columns and define column combinations that sum up to the full width of 12. The following figure illustrates some of these combinations: 12 columns of width 1, 6 columns of width 2, 4 columns of width 3, and so on. Also other combinations that sum up to 12 are allowed, such as 2, 6 and 4 or 1, 10 and 1 and many more.
Grid layout with 12 columns
Let's start and build the .row class that spans to the full width of the parent element:
Next, we want to create column classes .col-1, .col-2, .…, and .col-12 that define the width of the column in the percent relative to the width of the row. We define a text wrap with the floatattribute and add padding for the cells. The float attribute indicates that the block element should not appear in the original flow but "float" on the left side. By doing so, we align the elements in the same line instead of placing them into the normal text flow: