OpenFlashChart
Web上でグラフ表示が簡単にできるOpenFlashChartを紹介します。
1-1.プロジェクトの生成
(1) プロジェクトAppli024を生成する
(2) 日本語環境の設定
(3) データベースの作成
テストをする場合はProject_testの環境で実施されるのでDBもそれに対応してください。(db:create:allの指定)
NetBeansで[Rakeタスクを実行/デバッグ..]を選択します。
フィルタ(F):
パラメータ(P):
一致するタスク(M):db:create:all
(in D:/Rails_Projects/Test000)
1-2.Open Flash Chartのインストール
(1) Open Flash Chartのダウンロード
Open Flash Chartはhttp://github.com/pullmonkey/open_flash_chartにあり、をクリックして、
ここから直接pullmonkey-open_flash_chart-1489b25.zipをダウンロードします。
(2) Open Flash Chartのインストール
解凍したフォルダをopen_flash_chartにリネームして/vendor/plugins/配下にコピーします。
(3) swfobject.jsファイルのコピー
プラグインに入っている/vendor/plugins/open_flash_chart/assets/javascripts/swfobject.js ファイルを /public/javascriptsディレクトリにコピーします。
(4) open-flash-chart.swfファイルのコピー
プラグインに入っている/vendor/plugins/open_flash_chart/assets/open-flash-chart.swf ファイルを /publicディレクトリにコピーします。
1-3.アプリケーションの作成
(1) scaffoldの利用
NetBeansで[生成..]を選択します。
ジェネレータ(G): scaffold
モデル(N):Sale
属性ペア(フィールド型)(A): sales_moon:date amount_of_sales:integer
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/sales
exists app/views/layouts/
exists test/functional/
exists test/unit/
create test/unit/helpers/
exists public/stylesheets/
create app/views/sales/index.html.erb
create app/views/sales/show.html.erb
create app/views/sales/new.html.erb
create app/views/sales/edit.html.erb
create app/views/layouts/sales.html.erb
create public/stylesheets/scaffold.css
create app/controllers/sales_controller.rb
create test/functional/sales_controller_test.rb
create app/helpers/sales_helper.rb
create test/unit/helpers/sales_helper_test.rb
route map.resources :sales
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/sale.rb
create test/unit/sale_test.rb
create test/fixtures/sales.yml
create db/migrate
create db/migrate/20100310054934_create_sales.rb
(2) マイグレーションの実行
NetBeansで[データベースマイグレーション]→[現在のバージョンへ]を選択します。
(in D:/Rails_Projects/Appli024)
== CreateSales: migrating ====================================================
-- create_table(:sales)
-> 0.1880s
== CreateSales: migrated (0.1880s) ===========================================
1-4.ルーティングの設定
グラフ表示のメソッドの起動をRESTfulから外したルーティング設定とします。
これによりhttp://127.0.0.1:3000/graph/:action/:idで目的のメソッドが起動できるようになります。
例えば、
http://127.0.0.1:3000/graph/line_graph → {:controller=>'sales', :action=>'line_graph'}
http://127.0.0.1:3000/graph/test_graph/1 → {:controller=>'sales', :action=>'test_graph'}
http://127.0.0.1:3000/graph/test_graph/2 → {:controller=>'sales', :action=>'test_graph'}
http://127.0.0.1:3000/graph/test1_code → {:controller=>'sales', :action=>'test1_code'}
http://127.0.0.1:3000/graph/test2_code → {:controller=>'sales', :action=>'test2_code'}
となります。
ActionController::Routing::Routes.draw do |map|
map resources :sales
:
:
# consider removing or commenting them out if you're using named routes and resources.map.connect '/graph/:action/:id', :controller => 'sales'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
1-5.棒グラフ
(1) コントローラの作成
class SalesController < ApplicationController
def test_graph
@graph = open_flash_chart_object(600,400, "/graph/test1_code")
enddef test1_code
title = Title.new("Bar Chart")
bar = Bar.new
bar.set_values([1,2,3,4,5,6,7,8,9])
chart = OpenFlashChart.new
chart.set_title(title)
chart.add_element(bar)
render :text => chart.to_s
end
:
:
end
(2) ビューの修正
<script type="text/javascript" src="/javascripts/swfobject.js"></script><%= @graph %>
(3) 動作確認
ブラウザからhttp://127.0.0.1:3000/graph/test1_graphで起動します。
このURLにより設定したルーティングに従って{:controller=>'sales', :action=>'test1_graph'}が起動されます。
(棒グラフ)
1-6.折れ線グラフ
(1) コントローラの作成
テストプログラムごとにコントローラとビューを書くのは大変です。少しロジックに手を入れてコーディングの量を減らしましょう。
class SalesController < ApplicationController
def test_graph
path="/graph/test" + params[:id].to_s + "_code"
@graph = open_flash_chart_object(600,400,path)
enddef test1_code
:
enddef test2_code
title = Title.new("Line Chart")
line = Line.new
line.set_values([1,6,2,7,3,8,4,9,5])
chart = OpenFlashChart.new
chart.set_title(title)
chart.add_element(line)
render :text => chart.to_s
end
:
:
end
(2) ビューの修正
コントローラのメソッドがtest_graph一本になり、ビューはそれに対応する一つのプログラムでOKとなります。
<script type="text/javascript" src="/javascripts/swfobject.js"></script><%= @graph %>
(3) 動作確認
ブラウザからhttp://127.0.0.1:3000/graph/test_graph/2で起動します。
このURLにより設定したルーティングに従って{:controller=>'sales', :action=>'test_graph'}が起動されます。
さらにtest_graphメソッドの中で/graph/test2_codeが呼ばれることになります。
(折れ線グラフ)
1-7.円グラフ
(1) コントローラの作成
class SalesController < ApplicationController
:
:
def test3_code
title = Title.new("Pie Chart")
pie = Pie.new
pie.start_angle = -90
pie.colours = ["#0000ff", "#00ff00", "#00ffff", "#ff0000", "#ff00ff"]
pie.values = [2, 3, 4, 5, 6]
chart = OpenFlashChart.new
chart.set_title(title)
chart.add_element(pie)
render :text => chart.to_s
end
:
:
end
(2) 動作確認
ブラウザからhttp://127.0.0.1:3000/graph/test_graph/3で起動します。
(円グラフ)
1-8.横棒グラフ
(1) コントローラの作成
ここで注意しなければならないのがデータ値は上から順に設定していますが、
class SalesController < ApplicationController
:
def test4_code
title = Title.new("Horizontal Bar chart Chart")
hbar = HBar.new
hbar.values = [HBarValue.new(0,4), HBarValue.new(4,8), HBarValue.new(8,11)]
chart = OpenFlashChart.new
chart.set_title(title)
chart.add_element(hbar)
x = XAxis.new
x.set_offset(false)
x.set_labels(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
chart.set_x_axis(x)
y = YAxis.new
y.set_offset(true)
y.set_labels(["Phase3", "Phase2", "Phase1"])
chart.set_y_axis(y)
render :text => chart.to_s
end
:
end
Y軸のラベルは下から設定していることです。
(2) 動作確認
ブラウザからhttp://127.0.0.1:3000/graph/test_graph/4で起動します。
(横棒グラフ)
1-9.データの登録
ブラウザからhttp://127.0.0.1:3000/sales/でアプリケーションを起動しテスト用の売上データを登録します。
sales_moon | amount_of_sales |
---|---|
2009-01 | 18,300,000 |
2009-02 | 14,900,000 |
2009-03 | 16,900,000 |
2009-04 | 9,800,000 |
2009-05 | 11,300,000 |
2009-06 | 12,500,000 |
2009-07 | 16,500,000 |
2009-08 | 15,200,000 |
2009-09 | 20,600,000 |
2009-10 | 23,100,000 |
2009-11 | 21,300,000 |
2009-12 | 20,000,000 |
2010-01 | 19,600,000 |
2010-02 | 15,200,000 |
2010-03 | 15,800,000 |
2010-04 | 13,300,000 |
2010-05 | 9,500,000 |
2010-06 | 8,800,000 |
2010-07 | 6,000,000 |
1-10.折れ線グラフによる売上推移表の作成
(1) コントローラの作成
class SalesController < ApplicationController
:
:
def line_graph
@graph = open_flash_chart_object(600,400,"/graph/line_graph_code")
enddef line_graph_code
# 2009年の売上のみ抽出
@sales=Sale.find(:all,
:conditions => ['sales_moon>? and sales_moon 'sales_moon')@amountofsales=[]
@salesmoon=[]
for i in 0..11 do
@amountofsales<<@sales[i][:amount_of_sales].to_i # 売上額を数値に変換
@salesmoon<<@sales[i][:sales_moon].to_s[2..6] # 売上月を文字列に変換
endtitle = Title.new("売上推移表")
line_pv = Line.new
line_pv.text = "売上額"
line_pv.width = 1
line_pv.colour = '#4682B4'
line_pv.dot_size = 2
line_pv.values = @amountofsales # 売上額データのセット# the X Axis Labels
x_labels = XAxisLabels.new# text: Label text
x_labels.labels = @salesmoon # X軸ラベルのセット# steps: show every other label
x_labels.set_steps(1)# color: HTML Hex colour
x_labels.set_colour('#0000ff')# size: Font size in pixels
x_labels.set_size(10)# rotate: String can be one of "vertical" "diaganol" or "horizontal"
x_labels.set_rotate('vertical')# Add the X Axis Labels to the X Axis
x = XAxis.new
x.set_labels(x_labels)y = YAxis.new
y.set_range(0,40000000,2000000) # Y軸基準データのセットx_legend = XLegend.new("Time")
x_legend.set_style('{font-size: 20px; color: #778877}')y_legend = YLegend.new("Amount")
y_legend.set_style('{font-size: 20px; color: #770077}')chart =OpenFlashChart.new
chart.set_title(title)
chart.set_x_legend(x_legend)
chart.set_y_legend(y_legend)
chart.x_axis = x
chart.y_axis = ychart.add_element(line_pv)
render :text => chart.to_s
end
:
:
end
(2) ビューの修正
<script type="text/javascript" src="/javascripts/swfobject.js"></script><%= @graph %>
(3) 動作確認
ブラウザからhttp://127.0.0.1:3000/graph/line_graphで起動します。
このURLにより設定したルーティングに従って{:controller=>'sales', :action=>'line_graph'}が起動されます。
(折れ線グラフ)
1-11.棒グラフによる売上前年比較表の作成
(1) コントローラの作成
class SalesController < ApplicationController
:
:
def bar_graph
@graph = open_flash_chart_object(600,400,"/graph/bar_graph_code")
end
def bar_graph_code
@sales2009=Sale.find(:all,
:conditions => ['sales_moon>? and sales_moon 'sales_moon')
@sales2010=Sale.find(:all,
:conditions => ['sales_moon>? and sales_moon 'sales_moon')
@amountofsales=[]
@amountofsales2=[]
@salesmoon=["01","02","03","04","05","06","07","08","09","10","11","12"]
for i in 0..11 do
@amountofsales<<@sales2009[i][:amount_of_sales].to_i
@amountofsales2<<@sales2010[i][:amount_of_sales].to_i if i < @sales2010.count
endtitle = Title.new("売上前年比較表")
bar = Bar.new
bar.values = @amountofsales
bar.tooltip = "前年
金額=#val#"
bar.colour = '#47092E'bar2 = Bar.new
bar2.values = @amountofsales2
bar2.tooltip = "当年
金額=#val#"
bar2.colour = '#CC2A43'# the X Axis Labels
x_labels = XAxisLabels.new# text: Label text
x_labels.labels = @salesmoon# steps: show every other label
x_labels.set_steps(1)# color: HTML Hex colour
x_labels.set_colour('#0000ff')# size: Font size in pixels
x_labels.set_size(10)# rotate: String can be one of "vertical" "diaganol" or "horizontal"
x_labels.set_rotate('vertical')# Add the X Axis Labels to the X Axis
x = XAxis.new
x.set_labels(x_labels)y = YAxis.new
y.set_range(0,40000000,2000000)x_legend = XLegend.new("Time")
x_legend.set_style('{font-size: 20px; color: #778877}')y_legend = YLegend.new("Amount")
y_legend.set_style('{font-size: 20px; color: #770077}')chart =OpenFlashChart.new
chart.set_title(title)
chart.set_x_legend(x_legend)
chart.set_y_legend(y_legend)
chart.x_axis = x
chart.y_axis = ychart.add_element(bar)
chart.add_element(bar2)render :text => chart.to_s
end
:
:
end
(2) ビューの修正
<script type="text/javascript" src="/javascripts/swfobject.js"></script><%= @graph %>
(3) 動作確認
ブラウザからhttp://127.0.0.1:3000/graph/bar_graphで起動します。
このURLにより設定したルーティングに従って{:controller=>'sales', :action=>'bar_graph'}が起動されます。
(棒グラフ)
2.Open Flash Chart 2の文法
2-1.JSON
Open Flash ChartはJSONジェイソン(JavaScript Object Notation)形式で記述されたグラフデータをJavaScriptが読み込みグラフ描画しています。
(1) データ型
データ型 | 例 |
---|---|
数値(整数、浮動小数点数) | 555, 1234.56 |
文字列(ダブルコーテーションで囲む) | "one" |
真偽値 | true, false |
配列 | ["one", "two", "three"] |
ハッシュ(キーは文字列のみ) | {"code":"A001", "name":"Apple", "price":250} |
null | null |
(2) グラフデータの構造
まず具体例として公式ページhttp://teethgrinder.co.uk/open-flash-chart-2/より抜粋したものを提示します。
新らたに出現したキーについてはコメントを入れました。
{
"title":{
"text": "Many data lines",
"style": "{font-size: 20px; color:#0000ff; font-family: Verdana; text-align: center;}"
},"y_legend":{
"text": "Open Flash Chart",
"style": "{color: #736AFF; font-size: 12px;}"
},"elements":[
{
"type": "bar", # "bar", "bar_glass", "bar_3d",...
"alpha": 0.5, # 透明度 0=>完全透明,1=>完全不透明
"colour": "#9933CC",
"text": "Page views",
"font-size": 10,
"values" : [9,6,7,9,5,7,6,9,7]
},
{
"type": "bar",
"alpha": 0.5,
"colour": "#CC9933",
"text": "Page views 2",
"font-size": 10,
"values" : [6,7,9,5,7,6,9,7,3]
}
],"x_axis":{
"stroke": 1, # x軸の幅
"tick_height": 10, # x軸メモリ線の長さ
"colour": "#d000d0",
"grid_colour": "#00ff00",
"labels": {
"labels": ["January","February","March","April","May","June","July","August","Spetember"]
}
},"y_axis":{
"stroke": 4, # y軸の幅
"tick_length": 3, # y軸メモリ線の長さ
"colour": "#d000d0",
"grid_colour": "#00ff00",
"offset": 0, # true=>棒と棒の間隔の半分を起点とする
# false=>x軸のラインを起点とする
"max": 20
}
}
(3) 公式ドキュメンテーション
http://teethgrinder.co.uk/open-flash-chart-2/doxygen/html/index.htmlに全てが記されていますので、
こちらを参照することで細かな設定が可能になります。
例えば、棒グラフは次のような種類が用意されています。
bar
bar_3d
bar_cylinder
bar_dome
bar_glass
bar_round
bar_round3d
bar_round_glass (公式ページではbar_rounded_glassとなっているがエラーします)
bar_sketch
(4) 詳細な設定
棒のひとつだけ色を変えてみましょう。
class SalesController < ApplicationController
:
:def test5_code
title = Title.new("Bar Chart")
bar = Bar.new
bar.type = "bar"
bar.alpha = 0.5
vals =[1,2,3,4]
tmp = BarValue.new(5) # 5番目のデータは細かな設定
tmp.set_colour("#ff0000")
vals << tmp
vals << [6,7,8,9]
vals = vals.flatten # 配列を平滑化
bar.values = valsx = XAxis.new
x.stroke = 1
x.tick_height = 10
x.offset = true
x.set_labels(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])y = YAxis.new
y.stroke = 1
y.tick_length = 10chart = OpenFlashChart.new
chart.set_title(title)
chart.x_axis = x
chart.y_axis = y
chart.add_element(bar)
render :text => chart.to_s
end
:
:
end
(5) 動作確認
ブラウザからhttp://127.0.0.1:3000/graph/test_graph/5で起動します。