Data Visualization with JavaScript
5/5
()
About this ebook
In Data Visualization with JavaScript, you’ll learn how to use JavaScript, HTML, and CSS to build practical visualizations for your data. Step-by-step examples walk you through creating, integrating, and debugging different types of visualizations and you'll be building basic visualizations (like bar, line, and scatter graphs) in no time.
You'll also learn how to:
–Create tree maps, heat maps, network graphs, word clouds, and timelines
–Map geographic data, and build sparklines and composite charts
–Add interactivity and retrieve data with AJAX
–Manage data in the browser and build data-driven web applications
–Harness the power of the Flotr2, Flot, Chronoline.js, D3.js, Underscore.js, and Backbone.js libraries
If you already know your way around building a web page but aren’t quite sure how to build a good visualization, Data Visualization with JavaScript will help you get your feet wet without throwing you into the deep end. You’ll soon be well on your way to creating simple, powerful data visualizations.
Related to Data Visualization with JavaScript
Related ebooks
The Basics of JavaScript Coding For Beginners: Learn Basic JavaScript Programming Concepts Rating: 0 out of 5 stars0 ratingsUltimate iOS App Development Guide Rating: 0 out of 5 stars0 ratingsAn iOS Developer's Guide to SwiftUI: Design and build beautiful apps quickly and easily with minimum code Rating: 0 out of 5 stars0 ratingsA Guide To All Programming and Coding Languages Rating: 0 out of 5 stars0 ratingsQuick Guide for Obtaining Free Remote Desktop Protocol (RDP) Services Rating: 0 out of 5 stars0 ratingsHacking with Kali Linux: A Beginner’s Guide to Cybersecurity and Penetration Testing Rating: 0 out of 5 stars0 ratingsArtificial Intelligence and Machine Learning Fundamentals: Course, #3 Rating: 0 out of 5 stars0 ratingsAlgorithm Standard Requirements Rating: 0 out of 5 stars0 ratingsUltimate SwiftUI Handbook for iOS Developers: A complete guide to native app development for iOS, macOS, watchOS, tvOS, and visionOS Rating: 0 out of 5 stars0 ratingsBuilding an Operating System with Rust: A Practical Guide Rating: 0 out of 5 stars0 ratingsEssential Computer Hardware: The Illustrated Guide to Understanding Computer Systems Rating: 0 out of 5 stars0 ratingsData Science Essentials: Machine Learning and Natural Language Processing Rating: 0 out of 5 stars0 ratingsHow Hackers Steal Wi-Fi Passwords and How to Stop Them: Hacking, #3 Rating: 0 out of 5 stars0 ratingsMonero (XMR): The Unseen World of Cryptocurrency Rating: 0 out of 5 stars0 ratingsCryptocurrency Trading Guide : Mastering the Cryptocurrency Market: Techniques and Tactics for Profitable Trading Rating: 0 out of 5 stars0 ratingsA Short Introduction to Databases Rating: 0 out of 5 stars0 ratingsEssential Computer Hardware: Understanding the Building Blocks of Modern Technology and Securing Your Digital World Rating: 0 out of 5 stars0 ratingsRobot Operating System: Mastering Autonomous Systems for Seamless Integration and Control Rating: 0 out of 5 stars0 ratingsModern Full-Stack React Projects: Build, maintain, and deploy modern web apps using MongoDB, Express, React, and Node.js Rating: 0 out of 5 stars0 ratingsElements of Android Q Rating: 0 out of 5 stars0 ratingsThe Web Circular Rating: 0 out of 5 stars0 ratingsThe Oracle Hacker's Handbook: Hacking and Defending Oracle Rating: 4 out of 5 stars4/5Sql : The Ultimate Beginner to Advanced Guide To Master SQL Quickly with Step-by-Step Practical Examples Rating: 0 out of 5 stars0 ratingsAndroid Studio Masterclass: Android IDE For App Developers Rating: 0 out of 5 stars0 ratingsCybersecurity: Building a Fortified Digital Environment Rating: 0 out of 5 stars0 ratingsLearning Web3 Development Rating: 0 out of 5 stars0 ratings
Data Visualization For You
Data Analytics for Beginners: Introduction to Data Analytics Rating: 4 out of 5 stars4/5Data Analytics & Visualization All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsTeach Yourself VISUALLY Power BI Rating: 0 out of 5 stars0 ratingsHow to Lie with Maps Rating: 4 out of 5 stars4/5Mining Social Media: Finding Stories in Internet Data Rating: 0 out of 5 stars0 ratingsData Visualization with Excel Dashboards and Reports Rating: 4 out of 5 stars4/5Tableau For Dummies Rating: 4 out of 5 stars4/5Visual Analytics with Tableau Rating: 0 out of 5 stars0 ratingsThe Big Book of Dashboards: Visualizing Your Data Using Real-World Business Scenarios Rating: 4 out of 5 stars4/5Effective Data Storytelling: How to Drive Change with Data, Narrative and Visuals Rating: 4 out of 5 stars4/5Data Science Essentials For Dummies Rating: 0 out of 5 stars0 ratingsWinning The Room: Creating and Delivering an Effective Data-Driven Presentation Rating: 0 out of 5 stars0 ratingsFunctional Aesthetics for Data Visualization Rating: 0 out of 5 stars0 ratingsLearning Tableau Rating: 0 out of 5 stars0 ratingsNo-Code Data Science: Mastering Advanced Analytics, Machine Learning, and Artificial Intelligence Rating: 5 out of 5 stars5/5How to be Clear and Compelling with Data: Principles, Practice and Getting Beyond the Basics Rating: 0 out of 5 stars0 ratingsMicrosoft Power Platform For Dummies Rating: 0 out of 5 stars0 ratingsR for Data Science Rating: 5 out of 5 stars5/5Data Structures & Algorithms Interview Questions You'll Most Likely Be Asked Rating: 1 out of 5 stars1/5Creating Data Stories with Tableau Public: Illustrate your data in a more interactive and interesting way using Tableau Public Rating: 0 out of 5 stars0 ratingsTableau 10 Business Intelligence Cookbook Rating: 0 out of 5 stars0 ratingsLearning Tableau 2019 - Third Edition: Tools for Business Intelligence, data prep, and visual analytics, 3rd Edition Rating: 0 out of 5 stars0 ratingsDeep Learning with Keras: Beginner’s Guide to Deep Learning with Keras Rating: 3 out of 5 stars3/5Data Visualization For Dummies Rating: 2 out of 5 stars2/5
Reviews for Data Visualization with JavaScript
3 ratings1 review
- Rating: 5 out of 5 stars5/5
Nov 13, 2024
Thank You This Is Very Good, Maybe This Can Help You
Download Full Ebook Very Detail Here :
https://amzn.to/3XOf46C
- You Can See Full Book/ebook Offline Any Time
- You Can Read All Important Knowledge Here
- You Can Become A Master In Your Business
Book preview
Data Visualization with JavaScript - Stephen A. Thomas
About the Author
Stephen A. Thomas specializes in frontend development at Georgia Tech’s Department of Education Technology and has developed complex JavaScript visualizations for the health-care and security industries. He writes and speaks about data visualization in publications and at conferences around the world.
About the Technical Reviewer
Chris Keen resides in Atlanta, Georgia, and has been writing JavaScript since 2004. Chris has had the honor of working on visualizations ranging from an SVG tweet map at Weather.com to full-blown interactive maps with Leaflet.js at Endgame Systems. Chris is currently infatuated with making data dashboards using Backbone, Epoxy, and D3. Chris recently founded Keen Concepts (http://keenconcepts.io/), and he consults on JavaScript-rich web applications.
Acknowledgments
Even though it’s been said many times, there’s no getting around the fact that a book is the work of many people other than the author. This book certainly wouldn’t have been possible without the patience of Seph and the other fine folks at No Starch Press. There simply is no better publisher for technical books. Kudos also to Chris for the technical review, though, of course, the remaining mistakes are mine alone. I owe a special thanks to NickC for his generosity; it’s such a pleasure to meet folks that appreciate the true community spirit of the Web and web development. Finally, shout-outs to the team developing the Open Academic Environment and my colleagues at the Georgia Institute of Technology; working with them is a true pleasure.
Introduction
It’s getting hard to ignore the importance of data in our lives. Data is critical to the largest social organizations in human history (giants like Facebook and Google), and its collection has widespread geopolitical implications, as we all saw with the NSA surveillance scandal. But it’s also getting easier to ignore the data itself. One estimate suggests that 99.5% of the data our systems collect goes to waste.
Data visualization is a tool that addresses this gap. Effective visualizations clarify; they transform abstract collections of numbers into shapes and forms that viewers quickly grasp and understand. The best visualizations impart this understanding intuitively. Viewers comprehend the data immediately—without thinking. This frees viewers to more fully consider the implications of the data: the stories it tells, the insights it reveals, or even the warnings it offers.
If you’re developing websites or web applications today, there’s a good chance you have data to communicate—data best presented in a good visualization. But how do you know what kind of visualization is appropriate? And even more importantly, how do you actually create one? In the chapters that follow, we explore dozens of different visualizations, techniques, and toolkits. Each example discusses the appropriateness of the visualization (and suggests possible alternatives) and provides step-by-step instructions for adding the visualization to your web pages.
The Book’s Philosophy
In creating this book, I’ve tried to follow four main principles to make sure it provides meaningful and practical guidance.
Implementation vs. Design
This book won’t teach you how to design data visualizations. Quite honestly, there are other authors far better qualified than me for that (Edward Tufte, for example). Instead, this book will focus on implementing visualizations. When appropriate, I’ll take a slightly bigger picture view to discuss the strengths and weaknesses of particular visualization strategies, but the main goal is to show you how to create a wide range of visualizations. (I recognize that sometimes the boss absolutely insists on a pie chart.)
Code vs. Styling
As you might guess from the title, this book focuses on how to use JavaScript code to create visualizations. The examples don’t assume you’re a JavaScript expert—and I’ll be sure to explain any code more complicated than a basic jQuery selector—but I won’t spend much time discussing styles for the visualizations. Fortunately, styling visualizations is pretty much the same as styling other web content. Basic experience with HTML and CSS will serve you well when you add visualizations to your pages.
Simple vs. Complex
Most of the book’s examples are simple, straightforward visualizations. Complex visualizations can be engaging and compelling, but studying a lot of advanced code usually isn’t the best way to learn the craft. In these examples, I’ll try to stay as simple as possible so you can clearly see how to use the various tools and techniques. Simple doesn’t mean boring, however, and even the simplest visualizations can be enlightening and inspiring.
Reality vs. an Ideal World
When you begin building your own visualizations, you’ll discover that the real world is rarely as kind as you’d wish. Open source libraries have bugs, third-party servers have security issues, and not every user has updated to the latest and greatest web browser. I’ve addressed these realities in the examples in this book. I’ll show you how to accommodate older browsers when it’s practical, how to comply with security constraints such as Cross-Origin Resource Sharing (CORS), and how to work around bugs in other folks’ code.
The Book’s Contents
The chapters that follow cover a variety of visualization techniques and the JavaScript libraries that we can use to implement them.
Chapter 1 begins with the most basic visualizations—static charts and plots—using the Flotr2 library.
Chapter 2 adds interactivity to the visualizations, giving users the chance to select content, zoom in, and track values. The chapter also shows how to retrieve data for visualizations directly from the Web. For variety, its examples use the Flot library, which is based on jQuery.
Chapter 3 looks at integrating multiple visualizations and with other content on a web page; it uses the jQuery sparklines library.
In Chapter 4, we consider visualizations other than standard charts and plots, including tree maps, heat maps, network graphs, and word clouds. Each example focuses on a particular JavaScript library designed specifically for the visualization type.
Chapter 5 covers time-based visualizations. It looks at several ways to visualize timelines, including traditional libraries; pure HTML, CSS, and JavaScript; and full-featured web components.
In Chapter 6, we consider geographic data as we look at different ways to incorporate maps into our visualizations.
Chapter 7 introduces the powerful D3.js library, a flexible and full-featured toolkit for building custom visualizations of almost any type.
Beginning in Chapter 8, we consider other aspects of web-based visualizations. This chapter shows off the Underscore.js library, which makes it easy to prepare the data that drives our visualizations.
Finally, Chapter 9 and Chapter 10 walk through the development of a complete, single-page web application that relies on data visualization. Here we’ll see how to use modern development tools such as Yeoman and the Backbone.js library.
Source Code for Examples
To make the text as clear and readable as possible, examples usually contain isolated snippets of JavaScript, plus occasional fragments of HTML or CSS. Complete source code for all examples is available on GitHub at http://jsDataV.is/source/.
Chapter 1. Graphing Data
Many people think of data visualization as intricate interactive graphics of dazzling complexity. Creating effective visualizations, however, doesn’t require Picasso’s artistic skill or Turing’s programming expertise. In fact, when you consider the ultimate purpose of data visualization—helping users understand data—simplicity is one of the most important features of an effective visualization. Simple, straightforward charts are often the easiest to understand.
After all, users have seen hundreds or thousands of bar charts, line charts, X/Y plots, and the like. They know the conventions that underlie these charts, so they can interpret a well-designed example effortlessly. If a simple, static chart presents the data best, use it. You’ll spend less effort creating your visualization, and your users will spend less effort trying to understand it.
There are many high-quality tools and libraries to help you get started with simple visualizations. With these tools, you can avoid reinventing the wheel, and you can be assured of a reasonably attractive presentation by sticking with the library defaults. We’ll look at several of these tools throughout the book, but for this chapter we’ll use the Flotr2 library (http://www.humblesoftware.com/flotr2/). Flotr2 makes it easy to add standard bar charts, line charts, and pie charts to any web page, and it also supports some less common chart types. We’ll take a look at all of these techniques in the examples that follow. Here’s what you’ll learn:
How to create a basic bar chart
How to plot continuous data with a line chart
How to emphasize fractions with a pie chart
How to plot X/Y data with a scatter chart
How to show magnitudes of X/Y data with a bubble chart
How to display multidimensional data with a radar chart
Creating a Basic Bar Chart
If you’re ever in doubt about what type of chart best explains your data, your first consideration should probably be the basic bar chart. We see bar charts so often that it’s easy to overlook how effective they can be. Bar charts can show the evolution of a value over time, or they can provide a straightforward comparison of multiple values. Let’s walk through the steps to build one.
Step 1: Include the Required JavaScript
Since we’re using the Flotr2 library to create the chart, we need to include that library in our web pages. The Flotr2 package isn’t currently popular enough for public content distribution networks, so you’ll need to download a copy and host it on your own web server. We’ll use the minimized version (flotr2.min.js) since it provides the best performance.
Flotr2 doesn’t require any other JavaScript libraries (such as jQuery), but it does rely on the HTML canvas feature. Major modern browsers (Safari, Chrome, Firefox) support canvas, but until version 9, Internet Explorer (IE) did not. Unfortunately, there are still millions of users with IE8 (or even earlier). To support those users, we can include an additional library (excanvas.min.js) in our pages. That library is available from Google (https://code.google.com/p/explorercanvas/). Start with the following skeleton for your HTML document:
lang=en
>
charset=utf-8
>
➊
src=js/flotr2.min.js
>
Since other browsers don’t need excanvas.min.js, we use some special markup at ➊ to make sure that only IE8 and earlier will load it. Also, notice that we’re including the JavaScript libraries at the end of the document. This approach lets the browser load the document’s entire HTML markup and begin laying out the page while it waits for the server to provide the JavaScript libraries.
Step 2: Set Aside a Element to Hold the Chart
Within our document, we need to create a
lang=en
>
charset=utf-8
>
id=chart
style=width:600px;height:300px;
>
src=js/flotr2.min.js
>
Note that we’ve given the
chart) so we can reference it later. You’ll need to use a basic template like this (importing the Flotr2 library and setting up the
Step 3: Define the Data
Now we can tackle the data that we want to display. For this example, I’ll use the number of Manchester City wins in the English Premier League for the past seven years. Of course you’ll want to substitute your actual data values, either with inline JavaScript (like the following example) or by another means (such as an AJAX call to the server).
wins = [[[2006,13],[2007,11],[2008,15],[2009,15],[2010,18],[2011,21
],
[
2012,28
]]];
<
/script>
As you can see, we have three layers of arrays. Let’s start from the inside and work our way out. For Flotr2 charts, each data point is entered in a two-item array with an x-value and y-value. In our case we’re using the year as the x-value and the number of wins as the y-value. We collect all these values in another array called a series. We place this series inside one more outer array. We could enter multiple series into this outer array, but for now we’re showing only one series. Here’s a quick summary of each layer:
Each data point consists of an x-value and a y-value packaged in an array.
Each series consists of a set of data points packaged in an array.
The data to chart consists of one or more series packaged in an array.
Step 4: Draw the Chart
That’s all the setup we need. A simple call to the Flotr2 library, as shown here, creates our first attempt at a chart.
window.onload = function
() {
Flotr.draw
(
document.getElementById(chart
),
wins,
{
bars
: {
show: true
}
}
);
};
First we make sure the browser has loaded our document; otherwise, the chart
Since Flotr2 doesn’t require jQuery, we haven’t taken advantage of any of jQuery’s shortcuts in this example. If your page already includes jQuery, you can use the standard jQuery conventions for the Flotr2 charts in this chapter to execute the script after the window has loaded, and to find the
Figure 1-1 shows what you’ll see on the web page.
The Flotr2 library turns data into a basic (if unpolished) bar chart.Figure 1-1. The Flotr2 library turns data into a basic (if unpolished) bar chart.
Now you have a bar chart, but it’s not showing the information very effectively. Let’s add some options incrementally until we get what we want.
Step 5: Fix the Vertical Axis
The most glaring problem with the vertical axis is its scale. By default, Flotr2 automatically calculates the range of the axis from the minimum and maximum values in the data. In our case the minimum value is 11 wins (from 2007), so Flotr2 dutifully uses that as its y-axis minimum. In bar charts, however, it’s almost always best to make 0 the y-axis minimum. If you don’t use 0, you risk overemphasizing the differences between values and confusing your users. Anyone who glances at the chart in Figure 1-1, for example, might think that Manchester City did not win any matches in 2007. That certainly wouldn’t do the team any justice.
Another problem with the vertical axis is the formatting. Flotr2 defaults to a precision of one decimal place, so it adds the superfluous .0
to all the labels. We can fix both of these problems by specifying some y-axis options.
Flotr.draw(document.getElementById(chart
), [wins], {
bars
: {
show: true
},
yaxis
: {
min: 0
,
tickDecimals: 0
}
});
The min property sets the minimum value for the y-axis, and the tickDecimals property tells Flotr2 how many decimal places to show for the labels. In our case we don’t want any decimal places.
As you can see in Figure 1-2, adding these options definitely improves the vertical axis since the values now start at zero and are formatted appropriately for integers.
Simple options help Flotr2 construct a better vertical axis.Figure 1-2. Simple options help Flotr2 construct a better vertical axis.
Step 6: Fix the Horizontal Axis
The horizontal axis needs some work as well. Just as with the y-axis, Flotr2 assumes that the x-axis values are real numbers and shows one decimal place in the labels. Since we’re charting years, we could simply set the precision to 0, as we did for the y-axis. But that’s not a very general solution, since it won’t work when the x-values are non-numeric categories (like team names). For the more general case, let’s first change our data to use simple numbers rather than years for the x-values. Then we’ll create an array that maps those simple numbers to arbitrary strings, which we can use as labels.
var wins = [[[0,13],[1,11],[2,15],[3,15],[4,18],[5,21],[6,28]]]; var
years = [
[
0, 2006
],
[
1, 2007
],
[
2, 2008
],
[
3, 2009
],
[
4, 2010
],
[
5, 2011
],
[
6, 2012
]
];
As you can see, instead of using the actual years for the x-values, we’re simply using 0, 1, 2, and so on. We then define a second array that maps those integer values to strings. Although here our strings are years (and thus numbers), they could be anything.
Another problem is a lack of spacing between the bars. By default, each bar takes up its full horizontal space, but that makes the chart look very cramped. We can adjust that with the barWidth property. Let’s set it to 0.5 so that each bar takes up only half the available space.
Here’s how we pass those options to Flotr2.
Flotr.draw(document.getElementById(chart
), wins, {
bars
: {
show: true
,
barWidth: 0.5
},
yaxis
: {
min: 0
,
tickDecimals: 0
},
xaxis
: {
➊
ticks
: years
}
});
Note at ➊ that we use the ticks property of the x-axis to tell Flotr2 which labels match which x-values. Now we’re starting to get somewhere with our chart, as shown in Figure 1-3. The x-axis labels are appropriate for years, and there is space between the bars to improve the chart’s legibility.
We can define our own labels for the horizontal axis.Figure 1-3. We can define our own labels for the horizontal axis.
Step 7: Adjust the Styling
Now that the chart is functional and readable, we can pay some attention to the aesthetics. Let’s add a title, get rid of the unnecessary grid lines, and adjust the coloring of the bars.
Flotr.draw(document.getElementById(chart
), wins, {
title: Manchester City Wins
,
colors: [#89AFD2
],
bars
: {
show: true
,
barWidth: 0.5
,
shadowSize: 0
,
fillOpacity: 1
,
lineWidth: 0
},
yaxis
: {
min: 0
,
tickDecimals: 0
},
xaxis
: {
ticks
: years
},
grid
: {
horizontalLines: false
,
verticalLines: false
}
});
As you can see in Figure 1-4, we now have a bar chart that Manchester City fans can be proud of.
Additional options let us adjust the visual styles of the chart.Figure 1-4. Additional options let us adjust the visual styles of the chart.
For any data set of moderate size, the standard bar chart is often the most effective visualization. Users are already familiar with its conventions, so they don’t have to put any extra effort into understanding the format. The bars themselves offer a clear visual contrast with the background, and they use a single linear dimension (height) to show differences between values, so users easily grasp the salient data.
Step 8: Vary the Bar Color
So far our chart has been monochromatic. That makes sense because we’re showing the same value (Manchester City wins) across time. But bar charts are also good for comparing different values. Suppose, for example, we wanted to show the total wins for multiple teams in one year. In that case, it makes sense to use a different color for each team’s bar. Let’s go over how we can do that.
First we need to restructure the data somewhat. Previously we’ve shown only a single series. Now we want a different series for each team. Creating multiple series lets Flotr2 color each independently. The following example shows how the new data series compares with the old. We’ve left the wins array in the code for comparison, but it’s the wins2 array that we’re going to show now. Notice how the nesting of the arrays changes. Also, we’re going to label each bar with the team abbreviation instead of the year.
var wins = [[[0,13],[1,11],[2,15],[3,15],[4,18],[5,21],[6,28]]]; var wins2 = [[[0,28]],[[1,28]],[[2,21]],[[3,20]],[[4,19]]]; var
teams = [
[
0, MCI
],
[
1, MUN
],
[
2, ARS
],
[
3, TOT
],
[
4, NEW
]
];
With those changes, our data is structured appropriately, and we can ask Flotr2 to draw the chart. When we do that, let’s use different colors for each team. Everything else is the same as before.
Flotr.draw(document.getElementById(chart
), wins2, {
title: Premier League Wins (2011-2012)
,
colors: [#89AFD2
, #1D1D1D
, #DF021D
, #0E204B
, #E67840
],
bars
: {
show: true
,
barWidth: 0.5
,
shadowSize: 0
,
fillOpacity: 1
,
lineWidth: 0
},
yaxis
: {
min: 0
,
tickDecimals: 0
},
xaxis
: {
ticks
: teams
},
grid
: {
horizontalLines: false
,
verticalLines: false
}
});
As you can see in Figure 1-5, with a few minor adjustments we’ve completely changed the focus of our bar chart. Instead of showing a single team at different points in time, we’re now comparing different teams at the same point in time. That’s the versatility of a simple bar chart.
Bar charts can compare different quantities at one point in time as well as the same quantity at different points in time.Figure 1-5. Bar charts can compare different quantities at one point in time as well as the same quantity at different points in time.
We’ve used a lot of different code fragments to put together these examples. If you want to see a complete example in a single file, check out this book’s source code at http://jsDataV.is/source/.
Step 9: Work Around Flotr2 Bugs
If you’re building large web pages with a lot of content, you may run into a Flotr2 bug
that can be quite annoying. I’ve put bug
in quotation marks because the Flotr2 behavior is deliberate, but I believe it’s not correct. In the process of constructing its charts, Flotr2 creates dummy HTML elements so it can calculate their sizes. Flotr2 doesn’t intend these dummy elements to be visible on the page, so it hides
them by positioning them off the screen. Unfortunately, what Flotr2 thinks is off the screen isn’t always. Specifically, line 2,281 of flotr2.js is:
D.setStyles(div, { position
: absolute
, top
: -10000px
});
Flotr2 intends to place these dummy elements 10,000 pixels above the top of the browser window. However, CSS absolute positioning can be relative to the containing element, which is not always the browser window. So if your document is more than 10,000 pixels high, you may find Flotr2 scattering text in random-looking locations throughout the page. There are a couple of ways to work around this bug, at least until the Flotr2 code is revised.
One option is to modify the code yourself. Flotr2 is open source, so you can freely download the full source code and modify it appropriately. One simple modification would position the dummy elements far to the right or left rather than above. Instead of top
you could change the code to right
. If you’re not comfortable making changes to the library’s source code, another option is to find and hide those dummy elements yourself. You should do this after you’ve called Flotr.draw() for the last time. The latest version of jQuery can banish these extraneous elements with the following statement:
$(.flotr-dummy-div
).parent().hide();
Plotting Continuous Data with a Line Chart
Bar charts work great for visualizing a modest amount of data, but for more significant amounts of data, a line chart can present the information much more effectively. Line charts are especially good at revealing overall trends in data without bogging the user down in individual data points.
For our example, we’ll look at two measures that may be related: carbon dioxide (CO2) concentration in the atmosphere and global temperatures. We want to show how both measures have changed over time, and we’d like to see how strongly related the values are. A line chart is a perfect visualization tool for looking at these trends.
Just like for the bar chart, you’ll need to include the Flotr2 library in your web page and create a
Step 1: Define the Data
We’ll begin with CO2 concentration measurements. The US National Oceanographic and Atmospheric Administration (NOAA) publishes measurements (http://www.esrl.noaa.gov/gmd/ccgg/trends/co2_data_mlo.html) taken at Mauna Loa, Hawaii, from 1959 to the present day. The first few values are shown in the following excerpt.
var
co2 = [
[
1959, 315.97
],
[
1960, 316.91
],
[
1961, 317.64
],
[
1962, 318.45
],
// Data set continues...
NOAA also publishes measurements of mean global surface temperature (http://www.ncdc.noaa.gov/cmb-faq/anomalies.php). These values measure the difference from the baseline, which is currently taken to be the average temperature over the entire 20th century. Since the CO2 measurements begin in 1959, we’ll use that as our starting point for temperature as well.
var
temp = [
[
1959, 0.0776
],
[
1960, 0.0280
],
[
1961, 0.1028
],
[
1962, 0.1289
],
// Data set continues...
Step 2: Graph the CO2 Data
Graphing one data set is quite easy with Flotr2. We simply call the draw() method of the Flotr object. The only parameters the method requires are a reference to the HTML element in which to place the graph, and the data itself. The lines property of the data object indicates that we want a line chart.
Flotr.draw
(
document.getElementById(chart
),
[{
data: co2, lines: {show:true
} }]
);
Since Flotr2 does not require jQuery, we’re not using any jQuery convenience functions in our example. If you do have jQuery on your pages, you can simplify the preceding code a little. In either case, Figure 1-6 shows the result.
The first chart shows one data set.Figure 1-6. The first chart shows one data set.
The chart clearly shows the trend in CO2 concentration for the past 50-plus years.
Step 3: Add the Temperature Data
With a simple addition to our code, we can include temperature measurements in our chart.
Flotr.draw
(
document.getElementById(chart
),
[
{
data: co2, lines: {show:true
} },
{
data: temp, lines: {show:true}, yaxis: 2
}
]
);
Note that we include the yaxis option for the temperature data and give it a value of 2. That tells Flotr2 to use a different y-scale for the temperature data.
The chart in Figure 1-7 now shows both measurements for the years in question, but it’s gotten a little cramped and confusing. The values butt up against the edges of the chart, and the grid lines are hard for users to interpret when there are multiple vertical axes.
A single chart can show multiple data sets.Figure 1-7. A single chart can show multiple data sets.
Step 4: Improve the Chart’s Readability
By using more Flotr2 options, we can make several improvements in our line chart’s readability. First we can eliminate the grid lines, since they aren’t relevant for the temperature measurements.
We can also extend the range of both vertical axes to provide a bit of breathing room for the chart. Both of these changes are additional options to the draw() method.
Flotr.draw
(
document.getElementById(chart
),
[
{
data: co2, lines: {show:true
} },
{
data: temp, lines: {show:true}, yaxis: 2
}
],{
➊
grid: {horizontalLines: false, verticalLines: false
},
➋
yaxis: {min: 300, max: 400
},
➌
y2axis: {min: -0.15, max: 0.69
}
}
);
The grid options at ➊ turn off the grid lines by setting both the horizontalLines and verticalLines properties to false. The yaxis options at ➋ specify the minimum and maximum value for the first vertical axis (CO2 concentration), while the y2axis options at ➌ specify those values for the second vertical axis (temperature difference).
The resulting graph in Figure 1-8 is cleaner and easier to read.
Removing grid lines and expanding the axes makes the chart easier to read.Figure 1-8. Removing grid lines and expanding the axes makes the chart easier to read.
Step 5: Clarify the Temperature Measurements
The temperature measurements might still be confusing to users, since they’re not really temperatures; they’re actually deviations from the 20th-century average. Let’s convey that distinction by adding a line for that 20th-century average and explicitly labeling it. The simplest way to do that is to create a dummy
data set and add that to the chart. The extra data set has nothing but zeros.
var zero = []; for (var yr=1959; yr<2012; yr++) { zero.push([yr, 0]); };
When we add that data set to the chart, we need to indicate that it corresponds to the second y-axis. And since we want this line to appear as part of the chart framework rather than as another data set, let’s deemphasize it somewhat by setting its width to one pixel, coloring it dark gray, and disabling shadows.
Flotr.draw
(
document.getElementById(chart
),
[
{
data: zero, lines: {show:true, lineWidth: 1}, yaxis: 2
,
shadowSize: 0, color: #545454
},
{
data: co2, lines: {show:true
} },
{
data: temp, lines: {show:true}, yaxis: 2
}
],{
grid: {horizontalLines: false, verticalLines: false
},
yaxis: {min: 300, max: 400
},
y2axis: {min: -0.15, max: 0.69
}
}
);
As you can see, we’ve placed the zero line first among the data sets. With that order, Flotr2 will draw the actual data on top of the zero line, as shown in Figure 1-9, reinforcing its role as chart framework instead of data.
A dummy data set can emphasize a position on a chart axis.Figure 1-9. A dummy data set can emphasize a position on a chart axis.
Step 6: Label the Chart
For the last step in this example, we’ll add appropriate labels to the chart. That includes an overall title, as well as labels for individual data sets. And to make it clear which axis refers to temperature, we’ll add a °C
suffix to the temperature scale. We identify the label for each data series in the label option for that series. The overall chart title merits its own option, and we add the °C
suffix using a tickFormatter() function.
Flotr.draw
(
document.getElementById(chart
),
[ {
data
: zero,
label: 20th-Century Baseline Temperature
,
lines: {show:true, lineWidth: 1
},
shadowSize: 0
,
color: #545454
},
{
data
: temp,
label: Yearly Temperature Difference (°C)
,
lines: {show:true
}
},
{
data
: co2,
yaxis: 2
,
label: CO2 Concentration (ppm)
,
lines: {show:true
}
}
],
{
title: Global Temperature and CO2 Concentration (NOAA Data)
,
grid: {horizontalLines: false, verticalLines: false
},
y2axis: {min: -0.15, max: 0.69
,
➊
tickFormatter: function(val) {return val+ °C
;}}
yaxis: {min: 300, max: 400
},
}
);
For each value on the axis, the formatter function is called with the value, and Flotr2 expects it to return a string to use for the label. As you can see at ➊, we simply append the °C
string to the value.
Notice that we’ve also swapped the position of the CO2 and temperature graphs. We’re now passing the temperature data series ahead of the CO2 series. We did that so that the two temperature quantities (baseline and difference) appear next to each other in the legend, making their connection a little clearer to the user. And because the temperature now appears first in the legend, we’ve also swapped the axes, so the temperature axis is on the left. Finally, we’ve adjusted the title of the chart for the same reason. Figure 1-10 shows the result.
Labeling the axes and adding a legend completes the chart.Figure 1-10. Labeling the axes and adding a legend completes the chart.
A line chart like Figure 1-10 excels in visualizing this kind of data. Each data set contains over 50 points, making it impractical to present each individual point. And in fact, individual data points are not the focus of the visualization. Rather, we want to show trends—the trends of each data set as well as that data set’s correlation to the others. Connecting