#223
Jul 19, 2010

Charts

There are a number of libraries to help create graphs. Here I show how to integrate Highcharts into a Rails app.
Download (29.1 MB, 16:12)
alternative download for iPod & Apple TV (27.4 MB, 16:12)

Resources

<!-- layouts/application.html.erb -->
<%= javascript_include_tag "jquery-1.4.2.min", "rails", "highcharts" %>

<!-- orders/index.html.erb -->
<script type="text/javascript" charset="utf-8">
  $(function() {
    new Highcharts.Chart({
      chart: {
        renderTo: "orders_chart"
      },
      title: {
        text: "Orders by Day"
      },
      xAxis: {
        type: "datetime"
      },
      yAxis: {
        title: {
          text: "Dollars"
        }
      },
      tooltip: {
        formatter: function() {
          return Highcharts.dateFormat("%B %e, %Y", this.x) + ': ' +
            "$" + Highcharts.numberFormat(this.y, 2);
        }
      },
      series: [
      <% { "Download" => Order.download, "Shipping" => Order.shipping }.each do |name, orders| %>
      {
        name: "<%= name %>",
        pointInterval: <%= 1.day * 1000 %>,
        pointStart: <%= 3.weeks.ago.to_i * 1000 %>,
        data: <%= orders_chart_series(orders, 3.weeks.ago) %>
      },
      <% end %>
      ]
    });
  });
</script>
<div id="orders_chart" style="width:560px; height:300px;"></div>
# rails c
Order.group("date(purchased_at)").select("purchased_at, sum(total_price) as total_price").first.total_price.to_f
Order.group("date(purchased_at)").select("purchased_at, sum(total_price) as total_price").first.purchased_at.to_date

# models/order.rb
scope :shipping, where(:shipping => true)
scope :download, where(:shipping => false)

def self.total_on(date)
  where("date(purchased_at) = ?", date).sum(:total_price)
end

# orders_helper.rb
def orders_chart_series(orders, start_time)
  orders_by_day = orders.where(:purchased_at => start_time.beginning_of_day..Time.zone.now.end_of_day).
                  group("date(purchased_at)").
                  select("purchased_at, sum(total_price) as total_price")
  (start_time.to_date..Date.today).map do |date|
    order = orders_by_day.detect { |order| order.purchased_at.to_date == date }
    order && order.total_price.to_f || 0
  end.inspect
end

RSS Feed for Episode Comments 81 comments

1. Old Style Jul 19, 2010 at 04:07

I have been waiting for something like this one tutorial. Thanks!


2. mikhailov Jul 19, 2010 at 04:16

resources: http://railcsasts.com/episodes/205-unobtrusive-javascript isn't valid link, please fix it


3. Aaron M Jul 19, 2010 at 04:20

The domain in the link seems to be a typo.

I'll have to check this one out :).


4. Ryan Bigg Jul 19, 2010 at 04:35

You have an uncanny knack for picking up on some large topic discussed in the community each week and making a great Railscast out of it! Thanks Ryan!


5. valley Jul 19, 2010 at 04:42

I like jqPlot. Nice plugin architecture which can easily be extended.
The forum response is also quite good: http://www.jqplot.com/


6. Kosmas Chatzimichalis Jul 19, 2010 at 05:15

Great one as usual Ryan,

Thank you.

Just a small note about a problem with my firefox playing the video, and don't know if anyone else had that.
My firefox stops playing the video about 4 minutes before the end, just before displaying the console with all the different queries.
It's playing fine when I download it on my pc, and cannot remember having a similar problem with previous episodes.

Thanks again for the episodes Ryan.


7. xinuc Jul 19, 2010 at 05:32

Google chart api is pretty nice too
http://code.google.com/apis/charttools/index.html


8. mika Jul 19, 2010 at 05:47

i use xml/swf charts ( http://www.maani.us/xml_charts/ ) and it's good too (there is a plugin too for rails)


9. Branden Silva Jul 19, 2010 at 05:57

So I guess their aren't to many rails charts available eh? I guess it makes more sense that javascript handles this because of the animation involved but it would be nice to have a rails option where you can simply hook into jquery or something to spice it up.


10. Eduardo Fiorezi Jul 19, 2010 at 06:24

i use Google Visualization to generate my charts, http://code.google.com/apis/visualization/documentation/gallery.html

Javascript API.

Very nice railscast.


11. miguel michelson Jul 19, 2010 at 07:58

Hi Ryan, thank you very much for the mention of lazy_high_charts

best regards


12. Tom G Jul 19, 2010 at 08:32

There went ColdFusion developers' last excuse (cfchart) to switch to Rails. :-)


13. Ryan Bates Jul 19, 2010 at 09:10

@mikhailov, @Aaron, thanks, fixed!

@valley, cool, I haven't seen jqPlot before. It looks very nice. I'll add it to the links.

@Kosmas, if it always stops at 4 minutes then it sounds like a caching issue. The connection may have been dropped at that point and it continues to load from cache.

@Branden, there are a number of Rails plugins to hook into various charting libraries, but I find it often easier to interact directly with them.


14. Jim Jul 19, 2010 at 09:27

i've used jqplot before and it's really easy to customize. and thanks Ryan for this other option. :D keep this up!


15. louis Jul 19, 2010 at 09:31

I have been waiting so long for you new post !thank you !!


16. Stuart Chaney Jul 19, 2010 at 10:19

Exactly what I was looking for at that exact time as usual! Great stuff


17. Adilson Chacon Jul 19, 2010 at 10:25

Hi Ryan!

Have you ever met FusionCharts Free http://www.fusioncharts.com/free/ ?


18. Jônatas Davi Paganini Jul 19, 2010 at 10:55

I like so much how javascript libraries coming to be nice DSL's.

Thank you for this cool railscast!


19. Steve Byrne Jul 19, 2010 at 11:05

Thanks again Ryan for another great and informative railscast. Looking forward to playing around with the graphing libraries.

"Railscasts make Mondays worth looking forward to!"


20. John Jul 19, 2010 at 11:06

Unfortunately just too late; I just finished a project in which this would have been very useful!


21. dotemacs Jul 19, 2010 at 12:10

Not sure if its my setup: Ubuntu 9.10, but playing this with VLC 1.0.2 I keep getting glitches.

Apart from that, thanks Ryan, great railscast.


22. Florian Jul 19, 2010 at 13:11

I will have to generate some charts in the near future. So: Thank you once more.
Since I also will have to generate PDFs from the charts and I would like to use PDFKit for it, I did a simple test. I converted examples from the mentioned libraries with wkhtmltopdf (on the commandline, no fancy rails stuff, no additional parameters).
It seems, that only Highcharts generates vector shapes. All others generate low-res images.
If someone else is interested. Here are the PDFs:
http://qooy.com/files/DBX1VHNU/chart-pdf.zip


23. linki Jul 19, 2010 at 15:13

that's definitely one of your most awesome screencasts! keep on rocking, ryan.


24. dtolj Jul 19, 2010 at 15:17

Nice webcast, There is also another library that works nice with Ruby, http://teethgrinder.co.uk/open-flash-chart-2/
The site seems to be down, however.


25. dtolj Jul 19, 2010 at 15:37

I have a database table which is updated every 10sec, would love to see a dynamically updated page that keeps the graph information up to date.


26. robs Jul 19, 2010 at 16:17

@dtolj, I just noticed this in highchart's demo's:

http://www.highcharts.com/demo/?example=dynamic-update

Looks like the demo is just generating random points, but you may be able to tweak it for your needs.


27. Brian Doll Jul 19, 2010 at 16:58

At New Relic, we recently started using HighCharts to replace the Flash charts that have been in use for a while.

Everyone I've talked to about the new charts really loves them and they'll soon be the default in RPM.

The ability to toggle on and off a series of data is really sweet for complex charts, and since it's just JavaScript, they work really well on the iPhone and iPad, too.


28. B Jul 19, 2010 at 17:06

Great screenscast!! However, I would really love to see how I can select a timeline (week, month, year, custom dates) ...
Maybe in another one. Thank you!


29. Prabesh Shrestha Jul 19, 2010 at 22:04

As always great screencast. Thank you Ryan.


30. Martin Jul 20, 2010 at 00:50

Hey Ryan - as always a great cast :D

Lately I was refactoring the google_visualr rails plugin - a ruby wrapper for the google visualization api.

a gem could come up soon - clone the code from http://github.com/msalzburg/google_visualr


31. doabit Jul 20, 2010 at 01:28

Thank you ,i'm looking for that


32. Michael Jul 20, 2010 at 06:29

Thanks for this Ryan! Seeing it is so easy, maybe i am going to put this in some projects of mine.

I think railscasts.com is so usefull for this, showing the people all different kind of tactics and solutions to fix problems.

Thanks a lot!


33. Ryan Jul 20, 2010 at 09:54

Thanks Ryan, highcharts is awesome! I have used it quite a bit in the last couple of months - in fact I made a plugin (its rough haha) but can be found here http://github.com/loudpixel/highcharts-rails.


34. Ian Jul 20, 2010 at 14:39

Ryan,

FYI: Mike Nelson has implemented a Highcharts Prototype adapter.

http://github.com/mnelson/Prototype-Highcharts-Adapter/blob/master/highcharts-adapter.js


35. frank Jul 21, 2010 at 00:35

It is a nice recipes.

When i use Postgre as devlopment database ,Order.group("date(purchased_at)").select("purchased_at, sum(total_price) as total_price").first.total_price.to_f

will throw erro , i am just new user to Postgre, will someone help me ?


36. Nico Jul 21, 2010 at 08:57

I used used this rails plugin

http://github.com/Bantik/seer

It's another wrapper for the Google Visualization API. Works great.


37. elvankent halı yıkama Jul 22, 2010 at 00:11

Thank you.


38. Wes Garrison Jul 22, 2010 at 06:59

I've done a lot of charting for one of my projects:

* I need PDF reports, too. Javascript libraries are great for interactive in-the-page charts, but exporting them to a file and putting in a PDF isn't always the easiest.
* The google visualization API is okay, and you can grab the image from the URL and put it in a PDF.
* I like ChartDirector, easy to set up on a server, good ruby bindings and a responsive developer for questions.

Some JS libraries provide a .toPNG() function that could be used to grab the graph, so that's a possibility, but it might make more sense to use something that generates images, especially if you need crisp high-res images.


39. Florian Jul 22, 2010 at 10:05

@Wes Garrison
What about generating PDF-Report from HTML views with PDFKit.
I did some "research":
http://railscasts.com/episodes/223-charts#comment_116765


40. Hervé Jul 22, 2010 at 14:31

Simply brilliant! Thanks for yet another very useful and enlightening Railscasts.


41. apb gold Jul 22, 2010 at 18:56

Thanks for this Ryan! Seeing it is so easy, maybe i am going to put this in some projects of mine.

I think railscasts.com is so usefull for this, showing the people all different kind of tactics and solutions to fix problems.

Thanks a lot!


42. Les Jul 24, 2010 at 16:58

another source to add to your list is DHX:
http://www.dhtmlx.com


43. aza Jul 26, 2010 at 01:09

Super !!!


44. http://railscasts.com/tags/1 Jul 26, 2010 at 23:31

welcom to buy
Nike fivefingers kso nike runing shoes
Free shipping, cheaper price ,discount


45. hydra Jul 27, 2010 at 03:07

Nice screencast, it made me swap my charts in a current project from Seer to Highcharts.

Does anybody have an idea how to group the data by year|month|week instead of day?


46. File Recovery Software Jul 28, 2010 at 23:42

I use XML I think there are not many rails chart available. Please tell me it handles javascript or not?

Regards,
Data Recovery
http://www.datadoctor.biz


47. oakley sunglasses Jul 30, 2010 at 22:09

use XML I think there are not many rails chart available. Please tell me it handles javascript or not?


48. louboutins Aug 01, 2010 at 19:28

e XML I think there are not many rails chart available. Please tell me it handles javascript or not?


49. asian escorts detroit Aug 02, 2010 at 10:44

Very good document you may have penned. I found the subject very interesting generating for only a gratifying go through.

Locations additional that we consider you'll find important also
<strong><a href="http://www.2hotnsexy.com/Detroit/Escort-Agencies/tag/detroit-college-escorts/29/">detroit college escorts</a></strong>


50. acekard 2 Aug 02, 2010 at 20:20

thank you ,i am a seo,this help me a lot!
hi,i am a fan of nintendo and wii,so i always find <a href="http://www.ndscardstore.com/">acekard 2i</a> and other nds card on website,so i have brought so many cards from so much site,between those sites,recently i found two site with free shipping,and the cards is latest, between price and service,i chice the one blew:http://www.ndscardstore.com!


51. canli mac izle Aug 05, 2010 at 11:25

useful for me..thanks


53. Ken Aug 06, 2010 at 14:07

Love the railscasts, watch them every week. I implemented highcharts over the past few days and wanted to let you (and anyone else interested) know of a snag that I hit with the "orders_chart_series" method. Where you group and select the orders table for the variable "orders_by_day", I had to change :group => "date(purchased_at)" to :group => "DATE(CONVERT_TZ(purchased_at, '+00:00', '#{Time.zone.formatted_offset}'))". Same thing with the :select value. Without this, the records were falling in all utc dates.

FYI, this was all on rails 2.3.8, so maybe rails three does this automatically before executing the mysql statement.


53. Ken Aug 06, 2010 at 14:37

One last thing I wanted to tell you about the time zone issue I was having. This isn't a major issue, but if you want your highcharts' dates to line up properly, you should do this for the pointStart variable.

pointStart: <%= (3.weeks.ago.beginning_of_day + Time.zone.utc_offset).to_i * 1000 %>

Please let me know if these suggestions are incorrect. Thanks!


54. Ken Aug 06, 2010 at 14:57

Hate to clog up your comments thread, but there is a small mistake in the code I just posted, the Time.zone methods need to include the .now so it accounts for daylight savings. So, in the previous two posts, always use:

Time.zone.now.formatted_offset & Time.zone.now.utc_offset


55. cheap coogi Aug 09, 2010 at 10:19

Here we have popular Polo T-shirt.


56. UGG Boots on sale Aug 10, 2010 at 18:38

Gooooooooooooooooooood luck ~~!!!


57. jordan air force Aug 11, 2010 at 19:17

the article is amazing
the chat code is helpful for me
thanks for sharing


58. Replica Balenciaga bags Aug 13, 2010 at 03:12

the number of libraries to help create graphs is very useful to me. Here I learned how to integrate Highcharts into a Rails app.


59. fake Balenciaga bags Aug 13, 2010 at 03:13

all these were so wonderful ,thank you.


60. Replica Bally handbags Aug 13, 2010 at 03:15

thank you for sharing these useful informations.


61. Andro Aug 14, 2010 at 10:28

hey Ryan! - Great as always - THANK YOU!

Is there any way you are aware of to show multiple graphs in a view and be able to print to pdf?

Maybe it doesnt exist?!

Thanks again! ak.


62. oppo Aug 15, 2010 at 08:36

This was really useful. Thanks Ryan!


63. Rip Blu-ray for Mac Aug 18, 2010 at 01:24

Thanks,it's so good.
suport!


64. medyum hoca Aug 19, 2010 at 14:39

Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming


65. medyum Aug 19, 2010 at 14:40

Very nice sharing.thanks


66. wholesale new era caps Aug 20, 2010 at 19:56

I really liked your article and I shared with my friends in my facebook account ..
I gave my site a few examples below. If you appreciate my comments in you enter.


67. converse all star Aug 20, 2010 at 20:35

love converse all star,love yourself.Warm welcome.


68. converse all star Aug 20, 2010 at 20:54

love converse all star,love yourself.High quality low price.It's fit for you.


69. LH Aug 24, 2010 at 06:04

I'm a bit stuck converting the AREL methods back to Rails 2.3.8. I get the named_scopes bit, but I'm struggling with the self.total_on(date) and orders_chart_series methods. Can someone help by showing how this example can be converted for use in a Rails 2.3.8 project?


70. tile floor vacuum Aug 24, 2010 at 10:24

The blog article very surprised to me! Your writing is good. In this I learned a lot! Thank you!


71. cheap clothes Aug 24, 2010 at 19:05

David Heinemeier Hansson..thanks


72. PDF to Images Converter Aug 24, 2010 at 22:50

Some times, to a certain need, we have to convert PDF to image for enjoyment.


73. louis vuitton shoes Aug 26, 2010 at 23:21

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


74. mbt shoes sale Aug 28, 2010 at 10:01

Is there any way you are aware of to show multiple graphs in a view and be able to print to pdf?

Maybe it doesnt exist?!

Thanks again! ak.


75. cheap mbt shoes Aug 28, 2010 at 10:12

thank you for sharing these useful informations.


76. cheap ugg boots sale Aug 28, 2010 at 10:18

I gave my site a few examples below. If you appreciate my comments in you enter.


77. rap Aug 29, 2010 at 08:45

thank you for sharing these useful informations.


78. snow boots Aug 30, 2010 at 20:06

the respond_with(@product) shall produce an error I think (as the product has just been destroyed).


79. herve leger dress Aug 30, 2010 at 20:12

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it.


80. abercrombie and ftich Sep 01, 2010 at 07:08

thanks for sharing these useful informations.


81. levis belts Sep 01, 2010 at 20:54

Good article! Thank you so much for sharing this post.Your views truly open my mind.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source