简体   繁体   English

带有Ruby on Rails的Google Charts API

[英]Google Charts API with Ruby on Rails

I would like to graph time-series data like the following, 我想绘制如下的时序数据,

   timestamp, temperature
   12-12-2013 05:05:05, 25.569
   12-12-2013 05:05:10, 25.570
   12-12-2013 05:05:15, 26.000

and I know I can create a chart with javascript, by just putting this into the view: 而且我知道我可以使用javascript创建图表,只需将其放入视图即可:

<head>
    <script type="text/javascript" src="https://www.google.com/jsapi" ></script>
    <script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart);
    function drawChart() {
     var data = google.visualization.arrayToDataTable([
    ['t', 'temperature', 'data'],
    ['2004',  1000,      400],
    ['2005',  1170,      460],
    ['2006',  660,       1120],
    ['2007',  1030,      540]
  ]);

  var options = {
    title: 'Company Performance'
  };

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}
   </script>
</head>

My ruby array looks like this, similar to the format in the above code: 我的ruby数组看起来像这样,类似于上面的代码中的格式:

  [['timestamp', 'temperature'], [12-12-2013 05:05:05, 25.569], [12-12-2013 05:05:10, 25.570]
   ... and so on]

Do I need to convert the time to epoch time to graph it order, and how do I insert a ruby declared variable in the above javascript? 我需要将时间转换为纪元时间才能绘制顺序图,如何在上面的javascript中插入ruby声明的变量? Or am I doing something wrong here? 还是我在这里做错了什么?

Thank you, any help is appreciated. 谢谢您的帮助。

When I solved this issue, I had some problems with dates, can't remember now what exactly. 当我解决此问题时,我在日期方面遇到了一些问题,现在不记得确切了。 But I've sent date from ruby as string like 但是我已经从ruby发送日期作为字符串

date_for_js = "#{year}, #{month-1}, #{day}"

and the data as 和数据为

points_by_dates << [date_for_js, user.points.to_i]

Then I created .html.erb file 然后我创建了.html.erb文件

<%= javascript_tag do %>
    google.load('visualization', '1.0', {'packages':['corechart'], 'language': '<%= @locale.code %>'});
    google.setOnLoadCallback(drawChart);

    function drawChart() {
            var progress_chart_data = new google.visualization.DataTable();
            progress_chart_data.addColumn('date', '<%=j t(".date") %>');
          progress_chart_data.addColumn('number', '<%=j t(".points") %>');
            var progress_ticks = [];
            <% @points_by_dates.each_with_index do |points_by_date, index| %>
                progress_chart_data.addRow([new Date(<%= points_by_date[0] %>), <%= points_by_date[1] %>]);
                progress_ticks[<%= index %>] = new Date(<%= points_by_date[0] %>);
            <% end %>

            var date_format = 'MMM yyyy';

            var progress_chart_options = {
                legend: {position: 'out'},
                axisTitlesPosition: 'out',
                width: '800px',
              height: '300',
              hAxis: {format: date_format, ticks: progress_ticks},
                colors: ['#63c6d9'],
                vAxis: {minValue: 0},
                chartArea: {left: 90, top: 10}
            };
            var formatter = new google.visualization.DateFormat({pattern: date_format});
        formatter.format(progress_chart_data, 0); // Apply formatter to first column

        <% if @points_by_dates.present? %>
                var progress_chart = new google.visualization.AreaChart(document.getElementById('progress_chart'));
            progress_chart.draw(progress_chart_data, progress_chart_options);
        <% end %>
    };
<% end -%>

where you define dates in ticks option. 在这里你定义在选择日期。

Hope that will be useful for you. 希望对您有用。

Answer for your second question ie How to enter this variable in javascript is to use gon gem https://github.com/gazay/gon . 回答第二个问题,即如何在javascript中输入此变量是使用gon gem https://github.com/gazay/gon Basically what it does is to create a variable named gon in window namespace for your javascript. 基本上,它的工作是在JavaScript的窗口名称空间中创建一个名为gon的变量。 Infact you may avoid this gem by making your own global variable inside script tags in view file and calling the helper which generate this array there. 实际上,您可以通过在视图文件中的脚本标记内创建自己的全局变量并调用在此处生成此数组的帮助器来避免使用该宝石。 But Gon is a neat way hence I prefer it 但是Gon是一种整洁的方式,所以我更喜欢

The arrayToDataTable method does not support dates, so you have to use a regular DataTable constructor instead: arrayToDataTable方法不支持日期,因此您必须使用常规的DataTable构造函数:

var data = new google.visualization.DataTable();
data.addColumn('date', 't');
data.addColumn('number', 'temperature');
data.addColumn('number', 'data');
data.addRows(/* output from Ruby */);

Your timestamps need to be output as javascript Date objects. 您的时间戳需要作为javascript Date对象输出。 You can do this either by using either Unix epoch time or by splitting up your timestamp into year, month, day, hour, minute, second. 您可以通过使用Unix纪元时间或将时间戳分为年,月,日,小时,分钟,秒来实现。 The format for using Unix epoch time is: 使用Unix纪元时间的格式为:

new Date(/* Unix epoch time */);

The format for year/month/day is: 年/月/日的格式为:

new Date(year, month, day, hour, minute, second);

where month is 0-indexed, so January is 0, February is 1...December is 11. 其中月份是0索引,所以一月是0,二月是1 ...十二月是11。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM