Reputation: 267
I want to display dynamic data via charts,graphs which is retrieved from database. There are various gems available like highcharts, google graphs, gruff library, etc. Can anyone please site an example how to retrieve data from database and use it to display charts,graphs using anyone of these gems/libraries ? Any help will useful.
Thanks
Upvotes: 1
Views: 5383
Reputation: 5352
Okay here's a perfect example. In an application I recently completed I wanted to get the statistics for all employees and their overtime hours. I also then got the summed total for all employees. I decided to use highcharts. I believe that the best thing going to represent charts and graphs. Has really good documentation to back it up as well.
Controller
class StatisticsController < ApplicationController
def index
@users = User.all
@shifts = Shift.scoped
end
end
index.html.erb
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<script>
$(function () {
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart:{
renderTo:'container',
type:'column'
},
title:{
text:'<%= Date.today.strftime("%B")%> Overtime'
},
xAxis:{
categories:[
'<%= Date.today.strftime("%B")%>'
]
},
yAxis:{
min:0,
title:{
text:'Hours'
}
},
legend:{
layout:'vertical',
backgroundColor:'#FFFFFF',
align:'left',
verticalAlign:'top',
x:100,
y:70,
floating:true,
shadow:true
},
tooltip:{
formatter:function () {
return '' +
'Hours' + ': ' + this.y;
},
credits:{
text:'SomeText.co.uk',
hreft:'http://wwww.putyourlinkhere.co.uk'
}
},
plotOptions:{
column:{
pointPadding:0.4,
borderWidth:0
}
},
series:[
<%@users.each do |user|%>
{
name:'<%= user.name%>',
data:[<%= user.shift.sum(:overtime)%>]
},
<% end %>
{
name:'Total',
data: [<%= @shifts.to_a.sum(&:overtime)%>],
color:'#FE9D00'
}
]
});
});
});
</script>
From this example you can see that the series
is what is going to represent your data that you want to display. I loop through all users and output their name along with summing their shift. Further down I then grab the total by getting all shifts and putting it into an array and summing the overtime.
Oh and also you will need to download highcharts and put all relevant files in your assets.
This should be a good enough example to get you going.
Upvotes: 5