« « Data Delver: Mark Schaver, Louisville Courier

Data Delver: Phil Meyer » »

Using Javascript for interactive Google charts

Posted by on Mar 29, 2010 in Blog, programming | No Comments
Want to provide interactive graphs to news consumers quickly and easily on platforms that simply don’t support Flash?  Enter the “hidden power of Javascript,” a key component of the Google Visualization API.  It was the subject of a recent “Lightning Talk” I gave at NICAR 2010 in Phoenix.  My slides and a more thorough walk-through are included below.

NICAR 2010: Hidden Power of Javascript



Intro to Javascript

I think Javascript is a language that’s worth a second glance from every journalist with a slight interest in the Web. We know it’s a good idea to understand how to embed a link, post a photo, etc. using HTML tags. Hopefully, you started to dig into CSS, and know about positioning and divs, which helps you to organize the look of a site. We’ve got the content, we’ve got the design that arranges the content. But, what the Web can do that our standard print publication can’t is allow for interaction. And that’s something Javascript is very useful for. I like to define this as “the triangle of Web savvy.” HTML, CSS, Javascript.

Javascript is a language that can grow with you — I’m learning new things about it every day. You can learn about advanced libraries, and my adventures with JQuery have opened up a whole new realm of possibilities for me, it’s probably my favorite concept I’m working on right now. But you don’t need to dig that deep to start doing cool stuff. For the sake of introduction, and this tutorial, we’re going to stick to a simpler version of Javascript, which primarily uses tags. That means text and self-explanatory code is enclosed in commands that come in <>. Include a “/” in your tag to close it. If you can embed a link into text, you can do this.

Let’s make an interactive bar graph in Javascript!

We’re going to use the Google Visualization API, an interactive graphing tool that allows you to quickly input your data, and spit out code to place on your site. We’ll make one simple bar graph using a few data points you type in, and then I’ll show you how to use the same technique for hundreds of data points, but make the computer do the repetitive stuff. Programmers are the good kind of lazy. Humans are good at the creative part of the job. So we’ll do that, and let the computer do the boring part that’s the same over and over and over– that’s what it’s good at.

My example plots the number of actors/actresses who were in a certain decade of life when they received an Academy Award for best/supporting actor/actress, but any set of numbers will do.

1. In a new window or tab, visit the Google Visualization API homepage. Select Bar Chart (not Bar Chart (Image)).

2. Click on the example. Let’s walk through it quickly. HTML and head tags enclosed in brackets are standard HTML formatting. Tag-based Javascript usually goes in the head of an HTML document — it’s easier to read that way. Just like you want to organize a story for easy reading, same goes with code. Here’s a quick overview of what we’re looking at. The first script line says “Hey, we’re using Javascript, and referring to this API.” Then, we close that instance of Javascript. Next line: reopen Javascript. Google.load allows us to denote what package we’re using. Function allows us to call a certain method in our program — a command that’s complicated enough to require multiple lines of code. Then, we give the program our table in code that it can understand. Much of programming for data journalism requires formatting data in a way the program can understand. More complicated programs may accept more formats, but the learning curve’s a bit higher. This graph is fairly simple, but limited in how it can accept data. Very few charts in the Google API accept CSV format, you’ve got to input it the way it wants. Then, we close our tags, telling the server we’re done giving it Javascript. That’s it! Are we good to go, now? Great!

3. Just above this sample code, you’ll see a line of text with a link to the Google Visualization API playground. Click on it, or click here.

4. Now, you’ll see the code we were just looking at, but you can adjust it. Put the label for units of measurement in your y axis on line 4, replacing “year”, one series that will span your x axis in line 5, replacing ‘Sales’, and put a second series to be graphed across the x axis in line 6, replacing ‘Expenses’. If you’d like to eliminate the second series, delete line 6. To add more series, copy and paste line 5, and adjust accordingly. The terms ‘string’ and ‘number’ in rows 4-6 denote the type of data that will be found in that column. While the years are actually numbers, we’re not graphing them, they are merely text labels. So we put text in line 4, in the example. For lines 5 and 6, we are denoting columns filled with numerical data points, so those are ‘numbers.’

5. In line 7, change the number in the parentheses to the number of rows of data points you have in your data set. Here, we are telling the program what to expect.

6. Since I’m only using one series, I deleted rows 9, 12, 15, 18, 21. If you’re using two series, keep those rows. If you’re using more, you’ll need to add rows. The rows must stay in a specific order going year, series1, series2, series3, year, series1, series2, series3, etc.

7. Change the years to match the appropriate sequence. In my case, I’m looking at decades of life. So, my series are 10, 20, 30, 40, 50, 60, 70. Those numbers are placed in rows replacing years. These rows should be adjusted to follow the format “data.setValue(rownumber, 0, ‘numberinseries’). The series numbers for the y axis go in quotes, because we denoted them as text.

8. Fill in your series like you did in step 7. The middle number in parentheses should be 1 for the first series, 2 for the second, etc. This is equivalent to the column it would be in, in an actual data table. Here’s what mine looks like at this point.

code for data tables

9. At this point, you can test your graph by clicking the Run Code button at the top of the output box.

10. All that’s left is formatting the graph. I recommend replacing the draw (data) line with this code: “draw(data, {legend: ‘none’, width: 400, height: 240, is3D: true, title: ‘TITLEGOESHERE’});” This allow you to adjust the legend, I didn’t want one, but if you did, enter ‘left’, ‘center’ or ‘right to specify where it should go. Set the width and height of a graph, eliminate 3-D bars if you would like by setting is3D true or false, and setting a title. You can adjust many other parameters, which can be found by clicking view docs in the Edit Code box, and clicking on Configuration. Follow the format in the above line of code. It’s normally WhatIWantToAdjust:SOMENUMBER or ‘True’ or ‘False’ or ‘SOMETEXT’. One thing you may want to turn on or off is the tooltip, which displays the axis name, and exact number, when a user clicks on an individual bar. When you’re happy, press the Run Code button, and you’re good.

11. Just add this code into your HTML document, and you’re done. The graph will appear on your Web page just as it does in the playground. If you’d like Google to make the complete HTML document for you, click Edit HTML in the Edit Code box of the page, and then copy that complete text. (If you want to see a final product living in a page, check my example out here.)

Bonus trick: Automatically reformat data

“But, Michelle, I have hundreds of lines of data. Can’t I reformat my Excel file so the Google API, or other coding structures with similar limitations, can read it? Can’t the computer do this for me?”

Sure! This bar graph would get a little overwhelming with hundreds of data points, but there are other applications for the API where this would work, or be necessary. And if you wanted, you could do it. The graph would just extend very far down the page. This issue goes far beyond Javascript, and this simple trick has already saved me hours of repetitive work . Maybe it will help you, too. In this case, it will reduce the work for all the lines starting “data.setValue” — that’s steps 7 and 8. But you’ll need to do the rest, including the initial setup of specifying the headings and how many rows there are, using the instructions above.

To get this done, we’re going to treat the actual code as data in the same way we treat individual numbers as data. You can adapt this formula fairly often to get from an Excel spreadsheet to a TextEdit document of code.

1. Format your Excel spreadsheet so all of your years or other ‘text’ labels go down column A. Don’t put any headings above the data in other columns. Let B, C, etc. be full of data-only.

2. In a new column, paste this formula in the first cell (should be something-1.) =CONCATENATE(“data.setValue(“,ROW(A1),”,”,COLUMN(A1)-1,”,”,”‘”,A1,”‘”,”);”,”data.setValue(“,ROW(B1),”,”,COLUMN(B1)-1,”,”,”‘”,B1,”‘”,”);”,”data.setValue(“,ROW(C1),”,”,COLUMN(C1)-1,”,”,”‘”,C1,”‘”,”);”)

That concatenates, or combines the appropriate text with the row of the cell, column of the cell, and value of the cell. Copy from the last “data.setValue” to the end, and place a comma, and then the copied text, after the formula as is, if you need to add more columns. Adjust this for any code you want by simply looking at the code and breaking it down. It’s a great data exercise, making structured of the unstructured. Look at what stays the same, and what values you can use. Remember that when you add in straight text, it must be enclosed in quotes, and that every object that is concatenated must be separated by commas outside of all quotation marks.

3. Fill this formula down. Now you have code, but the code on each line contains all columns in that row. Every time you see a ;, that should be a new line. So, head to your nearest text editor that supports copying and pasting carriage returns. On a Mac, both TextEdit and TextMate will do the trick. I’m not sure about Windows, but just give any text editor a try. Microsoft Word won’t work for this.

4. Open a Find/Replace dialog box. Find all semicolons. (;) Replace with a semicolon, followed by a return. Get a return by hitting return in the text editor, copy that blank line, go to the replace form, enter a semicolon (;), paste in your blank line. Replace all, and the lines should separate into their proper pieces. This text replaces steps 7 and 8 in the above tutorial. Add this new text back into the code playground, adjust the other parts of the code and the parameters, and you are set.

Further reading

  • I live by the Head First Javascript book. Get a paper or e-book version.  Both well worth the money.  Actually, the Head First series in general is great for learning all sorts of things about programming.
  • W3 schools gives a nice, solid intro if you’re a beginner.
  • Check out Highcharts, another library for interactive Javascript charts. It uses many of the same techniques we’ve discussed here, but with some different options. I haven’t played with it as much, but it’s a great way to expand your toolset using what we’ve already gone over in this post.
« « Data Delver: Mark Schaver, Louisville Courier

Data Delver: Phil Meyer » »