bha*_*gav 1 google-visualization highcharts ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2
我想通过图表显示动态数据,图表是从数据库中检索的。有各种可用的gems,如highcharts、google graphs、gruff library等。 任何人都可以提供一个示例,如何从数据库中检索数据并使用它来显示图表,使用这些 gems/libraries 中的任何一个的图形?任何帮助都会有用。
谢谢
好的,这是一个完美的例子。在我最近完成的一个应用程序中,我想获得所有员工及其加班时间的统计数据。然后我还得到了所有员工的总和。我决定使用highcharts。我相信最好的东西将代表图表和图形。也有非常好的文档来支持它。
控制器
class StatisticsController < ApplicationController
def index
@users = User.all
@shifts = Shift.scoped
end
end
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
从这个示例中,您可以看到series将代表您想要显示的数据。我遍历所有用户并输出他们的姓名以及他们的班次总和。再往下,我通过获取所有班次并将其放入数组并总结加班时间来获取总数。
哦,您还需要下载highcharts并将所有相关文件放入您的资产中。
这应该是一个足够好的例子来帮助你前进。