2008 12 Web Grapher Eye Catching Graphics with the Google Charts Api


Eye-catching graphics with the Google Charts API
Web Grapher
The Google Chart API lets you draw custom graphs, charts, maps, and barcodes through a simple web
interface.
By Martin Streicher
auris, Fotolia, Fotolia
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¶meter2¶meterN 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.
Web Grapher 1
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,00FF
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.)
Figure 1: A sample line chart generated by the Google Chart API.
Listing 1: Auto Theft Trends in North Carolina
01 http://chart.apis.google.com/chart?
02 cht=lc&
03 chtt=Number of stolen autos in NC, by month and year&
04 chs=400x300&
05 chd=t:2231,1658,2156,2318,2343,2450,2583,2612,2522,2681,2326,2371|
06 2381,1939,2309,2242,2590,2642,2840,2837,2555,2558,2437,2319&
07 chds=0,3000&
08 chco=FF0000,0000FF&
09 chdl=2005|2006&
10 chxt=x,y&
11 chxl=0:|Jan|June|Dec|1:|0|1500|3000|&
12 chxp=0,0,50,100|1,0,50,100
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
Web Grapher 2
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.
Figure 2: The division of red (Republican) and blue (Democratic) states in the 2004 United States presidential
election.
Listing 2: Red and Blue States
01 http://chart.apis.google.com/chart?
02 cht=t&
03 chtm=usa&
04 chs=440x220&
05 chco=FF0000,0000FF,0000FF&
06 chld=CACTDEDCHIILMEMDMAMIMNNHNJNYORPARIVTWAWI&
07 chd=s:AAAAAAAAAAAAAAAAAAAA
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
Web Grapher 3
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.
Figure 3: The author's email address captured in a QR code.
Listing 3: Contact Information in a QR Code
01 http://chart.apis.google.com/chart?
02 cht=qr&
03 chs=200x200&
04 choe=UTF-8&
05 chld=Q&
06 chl=mailto:martin.streicher@gmail.com
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.
Figure 4: An entire vCard represented as a QR code.
Google Chart Tricks and Tips
The following tricks and tips will make your charts more readable:
Web Grapher 4
" 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.
http://chart.apis.google.com/chart?
cht=bvg&
chs=400x400&
chbh=40,5&
chd=t:30,45,51,53,60&
chp=.5&
chm=r,000000,0,.495,.5
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.
Web Grapher 5
Figure 5: Rendering positive and negative values in a bar chart.
Chart Your Heart Out
The Google Chart API is simple to use and easy to integrate into web applications. As shown here, you can
use the API immediately - just embed a static link in your web page and let the browser request and render a
chart each time the page is drawn.
To speed page rendering, you can request and cache the chart image on your own server, recreating the chart
only when the underlying data changes. In addition to providing better efficiency, this technique better
protects your raw data. A visitor to your site cannot "View Source" and copy the URL.
Of course, you can also mix the Google Chart API with AJAX techniques to modify charts on the fly in
response to user input. Chart Maker [6] is a basic but effective demonstration of dynamic charting; others
have used the Google Chart API to implement a loan calculator and executive dashboards.
Of course, Google Chart is often slower than charting tools that run on the desktop, such as Apple Numbers or
Microsoft Excel. These latter applications use native drawing engines and do not require an Internet round-trip
to transmit data and download a large graphic image. However, Google Chart is a free application that is
available from anywhere. If you are serious about using Google Chart in a production setting, pre-flighting
and caching can greatly improve response time.
INFO
[1] The pChart graphing framework for PHP: http://pchart.sourceforge.net/
[2] The Google Charts API documentation: http://code.google.com/apis/chart/
[3] BeeTagg: http://www.beetagg.com/
[4] Google's free Zebra Crossing barcode reader library: http://code.google.com/p/zxing/
[5] A guide to encoding data in QR codes: http://code.google.com/p/zxing/wiki/BarcodeContents
[6] A simple Google Chart generator: http://almaer.com/chartmaker/
[7] The JFreeChart charting library: http://www.jfree.org/jfreechart/
Web Grapher 6


Wyszukiwarka

Podobne podstrony:
GWT Working with the Google Web Toolkit (2006 05 31)
2008 11 Maximum Math Free Computer Algebra with Maxima
building web applications with the uml?2EDDA8
SEKTOR BANKOWY PODSTAWOWE DANE 2008 12 1 tcm75 9729
2008 12 Plumbers
FM GROUP?NNIK PRODUKTOW 12 WEB
2009 07 Weaving the Web Browser Synchronization and More with Mozilla Weave
Skanowanie 2008 12 13 16 37 (8)
Skanowanie 2008 12 13 16 37 (6)
Super8 and Tab Anjunabeats Worldwide 101 NET 2008 12 14 iRUSH
Nie zadzieraj z fryzjerem You Don t Mess with the Zohan [2008] HDTV
2008 02 Syncing It Syncing a Libferris Filesystem with an Xml File or Database

więcej podobnych podstron