Create a bar graph using Javascript, jQuery and flot

From Colettapedia
Jump to navigation Jump to search
$(function ()
{
  //debugger;

  var i;

  var class_wrapped_set = $("td.class");    
  var value_wrapped_set = $("td.value");

  var plot_points = [];

  for( i = 0; i < class_wrapped_set.size(); i++ )
    {
      plot_points.push([ parseFloat( class_wrapped_set[i].innerHTML ),
                         parseFloat( value_wrapped_set[i].innerHTML ) ]);
    }

  // dynamically figure out how wide the bars should be
  // find the minimum distance between x coordinates

  var min_x_distance;
  var temp_x_distance;

  if( plot_points.length > 1 )
  {
    min_x_distance = plot_points[1][0]-plot_points[0][0];
    for( var j = 2; j < plot_points.length; j++ )
    {
      temp_x_distance = plot_points[j][0] - plot_points[j-1][0];
      if( min_x_distance > temp_x_distance )
      {
        min_x_distance = temp_x_distance;
      }
    }
  }
  else
  {
    min_x_distance = 10; // arbitrary, hopoefully won't go here
  }

  var bar_width = min_x_distance / 2;
  
  var options =
    {
      label: "Interpolated Dose Responses",  
      series:
        {  
          data: plot_points
        },  
      bars: { show: true, barWidth: bar_width, align: "center" },  
      yaxis: { min: 0 },  
    };
  
    $.plot($("#placeholder"), [ plot_points ] , options);
});