mercoledì 17 dicembre 2008

Line graph with error band

Example of line graph with error band.
The function draws a series of quadrilaterals whose vertices matched pairs of the two series data_up and data_down then inserting a line is the average values.
To actually use series with variable error just simply change the code by passing the three sets as parameters instead generate randomly.


test_it_controller.rb

class TestItController < ApplicationController
def index
@graph1 = open_flash_chart_object(600,300,"/test_it/graph1_code")
end

def graph1_code

title = Title.new("a Graph")

chart = OpenFlashChart.new
chart.set_title(title)

@data_up = [1]
@data_down = [-1]

0.step(30, 1) {|i|
@data_up << @data_up[i] +rand - 0.5
@data_down << @data_down[i] + rand - 0.5
}

def draw_quadri(i)
q = Shape.new( '#80B11A' )
q.append_value(ShapePoint.new(i,@data_up[i]))
q.append_value(ShapePoint.new(i,@data_down[i]))
q.append_value(ShapePoint.new(i+1,@data_down[i+1]))
q.append_value(ShapePoint.new(i+1,@data_up[i+1]))
return q
end

flux = []
(@data_up.length-1).times do |h|
flux << draw_quadri(h)
end

flux.each do |shape|
chart.add_element(shape)
end

scatter_line = ScatterLine.new( '#FF0000', 5 )
scatter_line_u = ScatterLine.new( '#FF0000', 3 )
scatter_line_d = ScatterLine.new( '#FF0000', 3 )
data = []
data_u = []
data_d = []

x=0
(@data_up.length).times do |h|
data << (ScatterValue.new(x,(@data_up[h] + @data_down[h])/ 2))
data_u << (ScatterValue.new(x,@data_up[h]))
data_d << (ScatterValue.new(x,@data_down[h]))
x+=1
end

scatter_line.set_values(data); chart.add_element(scatter_line)
scatter_line_u.set_values(data_u); chart.add_element(scatter_line_u)
scatter_line_d.set_values(data_d); chart.add_element(scatter_line_d)

x = XAxis.new
x.set_range(0,32,5)
x.set_offset(false)
chart.set_x_axis(x)

y = YAxis.new
y.set_range(-5,5,1)
y.set_offset(true)
chart.set_y_axis(y)

render :text => chart.to_s
end
end

1 commento:

  1. Looks nice, but a live example would be welcome, specially for those not understanding the italian language that well ;-)

    RispondiElimina