Eye-catching graphics with the Google Charts API

Web Grapher

© auris, Fotolia, Fotolia

© auris, Fotolia, Fotolia

Article from Issue 97/2008

The Google Chart API lets you draw custom graphs, charts, maps, and barcodes through a simple web interface.

If a picture is worth a thousand words, a chart must be something akin to a novella. With just a glance, a chart can convey the state of the stock market, a trend in website traffic, the distribution of voters by county, and how monies are allocated in a household budget. Additionally, a chart is simply more memorable than a large table full of numbers.

Oddly, though, very few websites use charts to great advantage, largely because creating a chart requires unique programming and specialized, server-side software to render data. For example, if your site is based on PHP, you must install pChart [1] (or an analog), add the GD graphics library, and write code to produce a graphic of any kind. Ideally, any contributor – an editor, a writer, or a user adding comments – should be able to create and embed a chart.

Indeed, dynamism, simplicity, and convenience are at the heart of the Google Chart application programming interface (API) [2], perhaps more accurately described as software as a service (SaaS). Simply craft a parameterized URL in the form http://chart.apis.google.com/chart?parameter1&parameter2&parameterN and let Google Chart do all the heavy lifting. Google Chart lets you render six kinds of charts, a Google-o-meter, a QR code (a kind of barcode), and maps, and you can specify a googol of customizations, such as bar color, background color, legend, and more.

In this article, I'll help you get started with Google Chart. You'll learn how to draw charts and how to add special effects to improve your graphic creations.

Charting 101

To generate a chart with Google Chart, provide the prefix http://chart.apis.google.com/chart?, the chart type (such as pie or line), the size of the chart, your data, and any chart-specific parameters, such as colors and axis labels, to tailor the final result.

All chart options are set with key=value pairs. Some keys are common to all charts, whereas others are unique to a specific chart type. The syntax for the value specified in the pair tends to vary by chart type.

Chart size is measured in pixels and specified with the parameter chs=WxH, where W is the width and H is the height. For instance, chs=200x100 generates a chart 200 pixels wide and 100 pixels high. (The area of a map cannot exceed 440 pixels wide by 220 pixels high. For all other charts, width or height cannot exceed 1,000 pixels, and the maximum area is 300,000 square pixels.)

Chart type is chosen with cht=type, where type is one of several pre-defined constants. For example, to draw a simple line chart with equidistant points on the x-axis, specify cht=lc. For each chart type, you can find the appropriate constant in the Google Chart documentation.

Chart data may be provided in several formats – from a simple list of raw data, to a collection of alphanumeric codes to map values onto a predefined scale. Typically, a raw data set is a comma-separated list of values, and an encoded data set is a contiguous string of alphanumeric characters. For instance, to provide data as plain text, use chd= t:values, where values is a comma-delimited list of positive floating-point numbers between 0 and 100. The _ (underscore) may be used as a placeholder for a missing datum. Multiple data sets are delimited by the | (pipe or vertical bar).

To demonstrate, open a browser and type the URL http://chart.apis.google.com/chart?cht=lc&chs=500x400&chd=t:7,3,9,2,0,7,9|15,15,18,11,0,16,12&chco=FF0000,00FF00 into the address bar. As you might guess, the chco parameter lists RGB values to color each data set.

Figure 1 shows another example of a line chart, including labels. The URL used to generate the chart is shown in Listing 1. (Each URL shown in this article intentionally spans several lines for better readability.)

Listing 1

Auto Theft Trends in North Carolina


Briefly, chtt provides the chart title. The data is provided as raw values expressed in simple text, but because the values are larger than 100, chds provides a minimum and maximum value to normalize the data to a percentage. (Here, because the two data sets are within the same range, one minimum and maximum value suffices for both data sets. However, if each of your data sets is drawn from a unique range, provide a minimum and maximum value for each set.) The chxt parameter is combined with chxl and chxp to create and position the axis labels.

And believe it or not, drawing a chart is that simple! To embed a chart in a web page, use an img tag and set its src attribute to the URL of the chart. Provide a description of the chart in the alt attribute.

Map Maker

Drawing a map with the Google Chart service is as simple as drawing any other chart: First, specify the map chart, select a region of the world to draw, then associate data with each country, province, or state found in the map. Data can be discrete – say, to represent blue or red states in the United States – or continuous. Furthermore, you can associate a color with the minimum and maximum in a range and Google Chart renders intermediate values in graduated colors.

For example, Listing 2 generates a map of the United States, showing how states voted in the 2004 presidential election. Figure 2 presents the result.

Listing 2

Red and Blue States


In Listing 2, cht=t selects the map chart, chtm=usa chooses the United States as the region, and chs=440x220 draws the largest map possible. In the map chart, chco=FF0000,0000FF,0000FF specifies the default color of each state (red), and the beginning and end color (both blue) of the gradient.

The chld parameter contains the two-letter state code of each of the states won by the Democratic presidential candidate. Finally, chd=s: selects the simplified data encoding scheme, wherein all values must be represented by one of A-Z, a-z, and 0-9, where A is the minimum and 9 is the maximum. In other words, the simplified encoding scheme provides a granularity of 62 distinct values. Given that all states are colored red by default, any state with any other value – here, A – is colored blue.

Google Chart provides additional maps for Africa, Asia, Europe, the Middle East, South America, and the entire globe.

Swap Barcodes

In trendy Japan, kids share contact information in a truly digital fashion: they swap barcodes. And now you can, too. Google Chart provides an API to encode up to 4,296 characters in a two-dimensional, monochrome glyph called a QR code.

To begin, I'll encode my email address in a QR code. Listing 3 shows how the image in Figure 3 was created.

Listing 3

Contact Information in a QR Code


When you use the QR code chart, choe specifies the text encoding. The chld parameter dictates the amount of error correction provided in the image. (Q embeds enough duplicate information that 25 percent of the QR code can be destroyed without affecting readability.) chl is the text to encode, typically provided as a URL that is then interpreted by an application.

If you have a cell phone, you can download BeeTagg [3] for free, take a picture of Figure 3, and decode the results to send me an email message. (As an alternative, Google offers a free QR code reader library called Zebra Crossing [4][5] and an experimental online barcode reader that interprets images you upload.)

A QR code can capture up to 4,296 characters. Figure 4, for instance, encodes an entire vCard.

Google Chart Tricks and Tips

The following tricks and tips will make your charts more readable:

  • Be sure your chart size is wide enough to display the title, labels, and legend. Unfortunately, determining the minimum proper width is not algorithmic – you might need to use a little trial and error.
  • To alter the color and size of text in the chart title, use chts=color,fontsize. Also, you can change the color and font size of an axis label with chxs. Unfortunately, you cannot specify the typeface.
  • The four axes are x, t, y, and r, shorthand for bottom x-axis, top x-axis, left y-axis, and right y-axis, respectively. If you want multiple labels for any axis, repeat the axis name in the chxt parameter and specify its details in chxl.
  • Read the Google Chart API documentation carefully and pay particular attention to the syntax of each option. Even one typo can render a chart unreadable. For instance, the chd parameter uses the vertical bar to separate each set of data, yet chds does not. Unfortunately, this is not the only inconsistency in the Google Chart API (the clipping of bar charts is another), so keep the manual close by.
  • In the past, a bar chart with negative and positive values required hacks to render properly. Now you can use the chp parameter and a percentage to place the zero line a proportional distance from the origin on the y-axis. Values must then be interpolated to be rendered properly. For example, assume that cash flow in your company was (in millions) -20, -5, 1, 3, 10. To place the zero line at 0.5, or halfway up the y-axis, values less than 50 will be drawn "below the line," values of 50 "on the line," and all other values up to 100 "above the line." To normalize the data, add 50 to all values and plot the new values.

Figure 5 shows the finished chart.

The bvg parameter is the constant for the vertical bar chart type, and chd expresses the normalized data set. The chp parameter places the zero line halfway up the y-axis, whereas chm is an option to draw a range marker on the chart. Its parameters (in order) are r, for a horizontal marker; 000000 to draw the marker in black; 0, which is ignored; and .495 and .5 to express the bottom and top margins of the range marker as a proportion on the y-axis. Because the zero line is placed at 0.5, .495 and .5 draw a hairline at zero.

The chbh parameter specifies the width of a bar and the space between each bar. Unlike other chart types, if chbh is too large and chs is too small, some of your chart is clipped. Be sure to adjust one or both of these size parameters when drawing a bar chart.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Perl: Google Chart Instructions

    A CPAN module passes drawing instructions in object-oriented Perl to Google Chart, which draws visually attractive diagrams.

  • Tutorial – LibreOffice Charts

    Everybody needs charts sooner or later, and LibreOffice Calc is the easiest way to create them with free and open source software.

  • Perl: Pinpointing Spammers

    To identify the geographic regions from which link spam originated, a database locates IP addresses and the Google Charts service puts them onto a world map.

  • Wanderlust

    For running statistics on his recorded hiking trails, Mike Schilli turns to Go to extract the GPS data while relying on plotters and APIs for a bit of geoanalysis.

  • ProjectLibre

    ProjectLibre helps you organize and optimize a complex project with lots of moving parts.

comments powered by Disqus
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters

Support Our Work

Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

Learn More