Google Charts in Rails, gchartrb
3 Comments This week I was playing around with Google Charts, a wonderful API for creating charts via a URL. While I developed a helper class to create charts more easily in Rails, I did a little research and realized the RubyGem gchartrb has a great API for creating these charts. Here’s a quick tutorial on using gchartrb from the ground up.
Installing gchartrb
To install gchartrb, simply use the command gem install gchartrb from your command prompt. Check out these instructions for additional help and to access the gchartrb packages (Downloadable here).
Quick Examples
Now that we have our gem installed, we can create graphs right away. First, remember to require the gem at the top of your code. Notice how the gchartrb gem is actually called “google_chart”:
1 require 'rubygems'
2 require 'google_chart'
There are a couple ways that you can create a chart. You can instantiate the graph and then add attributes to it:
1 lc = GoogleChart::LineChart.new("400x200", "My Results", false)
Alternatively, you can create the graph and add the attributes within a block:
1 GoogleChart::LineChart.new("400x200", "My Results", false) do |lc|
2 # Put lc data here
3 # ...
4 puts lc.to_url
5 end
I personally prefer the latter method, as the creation of the graph and its attributes are kept together in a modular fashion.
Here are some examples of line, bar, and pie charts:
Line Chart
1 lc = GoogleChart::LineChart.new("400x200", "My Results", false)
2 lc.data "Line green", [3,5,1,9,0,2], '00ff00'
3 lc.data "Line red", [2,4,0,6,9,3], 'ff0000'
4 lc.axis :y, :range => [0,10], :font_size => 10, :alignment => :center
5 lc.show_legend = false
6 lc.shape_marker :circle, :color => '0000ff', :data_set_index => 0, :data_point_index => -1, :pixel_size => 10
7 puts lc.to_url
Notice that each lc.data call will create a new data line for you. The second parameter accepts a integer or float array, which can be anything you like. Lets say you have a WeighIn model that has weight as an attribute and belongs to some Person. If a person weighs himself/herself once a month for a year, then we can collect that data and show your trend via a line graph. Collecting that data and using it would look like this:
# In the controller Person
def show
@person = Person.find(params[:id])
weigh_ins = @person.weigh_ins.collect(&:weight)
lc = GoogleChart::LineChart.new("#{width}x200", "My Results", false)
lc.data "Weigh ins", weigh_ins, green
# etc, etc...
puts lc.to_url # Or @line_graph = lc.to_url
end
Another useful function, lc.axis, can be used to specify your own data range labels, but it is not required to create a chart (default ranges and labels will be used). The last function, lc.to_url, takes the information specified for the line chart and puts it into the Google charts url.
Bar Chart
1 bar_1_data = [350,110,700]
2 bar_2_data = [200,800,50]
3 color_1 = 'c53711'
4 color_2 = '0000ff'
5 names_array = ["Bob","Stella","Foo"]
6 GoogleChart::BarChart.new("600x300", "Horizontal Bar Graph", :horizontal, false) do |bc|
7 bc.data "FirstResultBar", bar_1_data, color_1
8 bc.data "SecondResultBar", bar_2_data, color_2
9 bc.axis :y, :labels => names_array, :font_size => 10
10 bc.axis :x, :range => [0,1000]
11 bc.show_legend = false
12 bc.stacked = true
13 bc.data_encoding = :extended
14 bc.shape_marker :circle, :color => '00ff00', :data_set_index => 0, :data_point_index => -1, :pixel_size => 10
15 puts bc.to_url
16 end
An interesting attribute to pay attention to is bc.stacked, which gives you the ability to stack bar data, or to create separate bars together. When bc.stacked = false, the chart above is what is shown.
If bc.stacked = true, the same data will look like this:
Also, if you wanted to use this code in one of your controllers, and then display the graph in a template (view) file, you would set the graph’s url in the controller: @graph = bc.to_url Then within the view, you can simple show the graph as an image like this:
<!-- From within the view file -->
<img src="<%= @graph %>"/>
Pie Chart
1 GoogleChart::PieChart.new('320x200', "Pie Chart",false) do |pc|
2 pc.data "Apples", 40
3 pc.data "Banana", 20
4 pc.data "Peach", 30
5 pc.data "Orange", 60
6 puts "\nPie Chart"
7 puts pc.to_url
8 # Pie Chart with no labels
9 pc.show_labels = false
10 puts "\nPie Chart (with no labels)"
11 puts pc.to_url
12 end
This last example was taken from gchartrb’s readme file, which has an example for each kind of chart you can create (including Venn diagrams, Scatter charts, XY Line charts, etc). Notice that the data does not need to be within 0 to 100 (like percents on the pie chart) – the data will be added together and scaled appropriately by gchartrb. If you want to make the chart 3d, either set the 3rd parameter on PieChart.new to true, or you can set the attribute manually: pc.is_3d = true
Useful parameters
Google charts, by default, works with the data range between 0 and 100. Most of the time, your values will not work with this same scale. Instead of converting your data to the default scale, you can specify the data range with the :range parameter in bc.axis. So if you data was between 1 and 12 on the x_axis (like months in a year), then you could specify that range like so:
lc.axis :x, :range => [1,12], :labels => month_names_array
If you’re working with large data sets/numbers, then you may have chart data that is slightly off the mark. The default encoding that gchartrb uses is called Simple Encoding, which only has 62 points of resolution. We can easily expand this resolution (to 4096 points of resolution) by using Extended encoding, which a chart can select by changing the data_encoding attribute with :extended. For a line graph lc, it would look like this: lc.data_encoding = :extended. See Chart data for an explanation for all the encodings Google charts uses.
gchartrb subtlities
While gchartrb provides a great API for create charts in Rails, there are some subtle details about gcharts that you should be aware of. First of all, all charts derive from the base class GoogleChart::Base – check it out to see all the methods and attributes that apply to all charts. Secondly, gchartrb encodes all of the data values in some_chart.data from numeric form into a string representation of the data. This conversion doesn’t effect the final output of your chart, and helps make the chart url shorter in length. Again, if your working with large values, make sure the use the extended coding by using lc.data_encoding :extended.
Other Resources
Now that you have a taste of Google Charts with gchartrb, check out the API documentation here. If gchartrb doesn’t suit your tastes, you can go directly to the Google Charts API – it is thorough and self-explanatory. Ajaxian shows a number of quick examples of Google Charts here, and Matthew Bass gives a solid introduction to Google Charts and a few examples with gchartrb here. Lastly, here is a great link for 50 Cool Things You Can Do with Google Charts.
Google Health
Comments Off Google health launched today and could be really big. The new Google product will let you store and manage all of your health information in one central place. I think this is a great step forward for the online medical community. Sites like webmd are very informative but not personal. I can only imagine the amount of data Google will be able to index now. But hey, it’s free.
I hope Google doesn’t drop the ball on the social side, because it could be really helpful to a lot of people. Let users rate and comment on doctors and perhaps even view your friend’s doctors. Let users exchange medical treatments they tried out and give first hand accounts of medications. I’m tired of going to sites that pretend to be informative when, in actuality, are trying to push a certain new medication or treatment process on you.
- Start tracking a medical history and learn about your conditions
- Import your medical records
- View your medical history
- Find out how medications might interact
- Make your health information work for you
- Search for doctors and hospitals
Find out more information here.
Google Charts API, examples.
Comments Off I was finally playing with the Google Charts API so I could learn it… I will forgo the hurdles and issues I have with it… I just wanted to dump out the examples I made while learning it– for future reference.
A simple line chart.
A New Way to look at Networking
Comments Off Van Jacobson has, in his Google TechTalk, many good quotes… my two favorite:
“Data’s got a name, not a location.” — Van Jacobson
“Data doesn’t live anywhere; where ever it is, it’s great.” — Van Jacobson
Tunnel to Gmail
1 Comment I am in Venezia, Italia and my host has graciously let me use her computer to check email. There’s only one problem… Google’s services (email, reader, hosted, analytics, etc) have been unavailable to me for the past five hours. There’s a problem upstream, somewhere, that prevents me from getting to GMail. A friend, in the Bay Area, tells me– over IM chat– that he has perfect access to GMail. All this tells me that it’s just a regional access thing.
Anyways, I really needed to check my email and couldn’t wait for the problem to get resolved. So I just worked up a quick hack.
First, I edited the laptop’s hosts file (c:/windows/system32/drivers/etc/hosts) to add the following lines:
127.0.0.1 google.com
127.0.0.1 www.google.com
127.0.0.1 mail.google.com
Second, I launched the signed-jar copy of Mindterm that I have sitting on my website; I logged in to my dreamhost shell account (in the States) and set up a couple of ssh tunnels that redirected web traffic from the local loopback address to google.com:
127.0.0.1 port 80 -> google.com port 80
127.0.0.1 port 443 -> google.com port 443
Finally, launched IE (she doesn’t have Firefox installed) for immediate access to GMail.
What did that really do?
Normal Case: IE talks directly to GMail. IE -> GMail.
But the Normal Case is broken.
My Workaround: IE talks to GMail through a third party. IE -> Dreamhost Server -> GMail.
Future Google Appliances
Comments Off Kevin Dangoor suggests that we may eventually see Google provide an appliance for all our office needs.
Then I remember Cringley’s article suggesting a Google home entertainment appliance.
I would enjoy having nice simple, affordable, appliances to make my life easier. Heck, even though I love mucking with computer tech, I hate to spend all my time doing it. IT takes a lot of time to deal with, especially if one’s plans involve maintaining other locations (eg other family member’s homes). So if Google can come out with an appliance (all-in-one) that services all my office, entertainment and IT management needs, I would be all over it. But a message to Google: I just want something nice– and would appeal to my geek aesthetics– to just work, without it encumbering upon my freedoms (open integration, avoid lock-in).
Atom Publish Protocol and GData
Comments Off The GData protocol introduced an optimistic locking convention, for resource editing, to the Atom Publish Protocol. The introduced method is quite simple: An Atom Entry’s edit URL is unique by version of the resource. Although the Google team’s method just added a version number to the end of the URL, the URL itself can be random and is opaque of semantic meaning. This versioned URL method allows the server to know if a client is trying to update a resource based on stale information.
After some pause, I had a question: Would it be better to have such versioned URLs or would it be better to add meta information in the Atom entry?
The APP draft spec states:
8.2.1 Editing entries with foreign markup
To avoid unintentional loss of data when editing entry collection
members, Atom Protocol clients SHOULD preserve all metadata,
including unknown foreign markup, that has not been intentionally
modified.
This means that an APP client will send back the version information even if it doesn’t know anything about versioning, which would allow for the server to detect version conflicts.
However, the metadata method’s one weakness is in that it only works with Atom Entries and will not work for other Media. Besides this, I have not found any compelling evidence to support one method or another when ignoring the metadata weakness. And I can’t see either method breaking the REST model, so maybe it’s up to the APP Service API designer.
Then my brain took a tangent:
Doesn’t having version based edit URLs (http://example.com/pic.jpg/1/ and http://example.com/pic.jpg/2/) imply that there are two separate resources as opposed to a single resource? In general, should different versions of a resource be modeled as separated resources? Yet aren’t we talking about editing a resource published at a single URL: http://example.com/pic.jpg ? If we have two separate resources, then shouldn’t the published (linked to in a blog entry) URL be the latest versioned URL (http://example.com/pic.jpg/2/)? Or can we say that http://example.com/pic.jpg represents the lastest version in the ‘trunk’? Or am I splitting hairs since they may just be two sides of the same coin?
Ah that’s it for thinking out loud…
Google Reader Tag Delete
Comments Off I guess I was asleep when the Google Reader team pushed out better management changes. I can easily delete labels now
.

Google Talk and AIM
Comments Off A press release announced the following:
Enabling Google Talk and AIM instant messaging users to communicate with each other, provided certain conditions are met
A nice first step. Let’s just hope that we can get AIM to use the open Jabber/XMPP protocol that Google uses. But I doubt that will happen anytime soon, if at all.
At the very least, I think I’ll be able to stop using my AIM account and just use Google Talk.
Google’s Internet
Comments Off Cringley’s latest post about Google focuses on a mystery shipping container found in a Google garage:
This shipping container is a prototype data center. Google hired a pair of very bright industrial designers to figure out how to cram the greatest number of CPUs, the most storage, memory and power support into a 20- or 40-foot box. We’re talking about 5000 Opteron processors and 3.5 petabytes of disk storage that can be dropped-off overnight by a tractor-trailer rig. The idea is to plant one of these puppies anywhere Google owns access to fiber, basically turning the entire Internet into a giant processing and storage grid.
He then explores what (and how) Google might make use of this grid (World Internet Domination). I’m still digesting what he has said for my own take, but my own gut reactions are:
- It’s not only a Data Center itself, but can be the key future building block for even larger Data Centers.
- Google may truely bring grid computing capabilities to the masses, something I don’t see Sun or IBM doing well.
- This is one big fun geek toy that I want to get my hands on.