ChartDirector 6.0 (Ruby Edition)

Simple Database Chart




In this example, we will demonstrate how to create a web page to show the monthly revenue for a given year. The user will select a year from a HTML form and press OK. The web server will query a database to obtain the necessary data, and return a web page containing the bar chart for the selected year.

Note that although the database sample codes are based on Ruby On Rails, the techniques are equally applicable to standalone Ruby applications.

[Ruby On Rails Version - Controller] app/controllers/dbdemo1_controller.rb
require("chartdirector")

class Dbdemo1Controller < ApplicationController

    def index()
        @ctrl_file = File.expand_path(__FILE__)
    end

    def getchart()
        selectedYear = params["year"] || "2001"

        #
        # Query database for the selected year and read results into arrays
        #

        records = Revenue.find(:all,
            :conditions => ["strftime('%Y', TimeStamp) = ?", selectedYear],
            :order => "TimeStamp")

        software = []
        hardware = []
        services = []
        records.each do |r|
            software.push(r.Software)
            hardware.push(r.Hardware)
            services.push(r.Services)
        end

        #
        # Now we have read data into arrays, we can draw the chart using ChartDirector
        #

        # Create a XYChart object of size 600 x 300 pixels, with a light grey (eeeeee) background,
        # black border, 1 pixel 3D border effect and rounded corners.
        c = ChartDirector::XYChart.new(600, 300, 0xeeeeee, 0x000000, 1)
        c.setRoundedFrame()

        # Set the plotarea at (60, 60) and of size 520 x 200 pixels. Set background color to white
        # (ffffff) and border and grid colors to grey (cccccc)
        c.setPlotArea(60, 60, 520, 200, 0xffffff, -1, 0xcccccc, 0xccccccc)

        # Add a title to the chart using 15pt Times Bold Italic font, with a light blue (ccccff)
        # background and with glass lighting effects.
        c.addTitle(sprintf("Global Revenue for Year %s", selectedYear), "timesbi.ttf", 15
            ).setBackground(0xccccff, 0x000000, ChartDirector::glassEffect())

        # Add a legend box at (70, 32) (top of the plotarea) with 9pt Arial Bold font
        c.addLegend(70, 32, false, "arialbd.ttf", 9).setBackground(ChartDirector::Transparent)

        # Add a stacked bar chart layer using the supplied data
        layer = c.addBarLayer2(ChartDirector::Stack)
        layer.addDataSet(software, 0xff0000, "Software")
        layer.addDataSet(hardware, 0x00ff00, "Hardware")
        layer.addDataSet(services, 0xffaa00, "Services")

        # Use soft lighting effect with light direction from the left
        layer.setBorderColor(ChartDirector::Transparent, ChartDirector::softLighting(
            ChartDirector::Left))

        # Set the x axis labels. In this example, the labels must be Jan - Dec.
        labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov",
            "Dec"]
        c.xAxis().setLabels(labels)

        # Draw the ticks between label positions (instead of at label positions)
        c.xAxis().setTickOffset(0.5)

        # Set the y axis title
        c.yAxis().setTitle("USD (Millions)")

        # Set axes width to 2 pixels
        c.xAxis().setWidth(2)
        c.yAxis().setWidth(2)

        # Output the chart in PNG format
        send_data(c.makeChart2(ChartDirector::PNG), :type => "image/png", :disposition => "inline")

    end

end

[Ruby On Rails Version - View] app/views/dbdemo1/index.html.erb
<html>
<body style="margin:5px 0px 0px 5px">
<div style="font-size:18pt; font-family:verdana; font-weight:bold">
    Database Integration Demo (1)
</div>
<hr style="border:solid 1px #000080" />
<div style="font-size:10pt; font-family:verdana; margin-bottom:20px">
<%= link_to "Source Code Listing", :controller => "cddemo", :action => "viewsource",
    :ctrl_file => @ctrl_file, :view_file => File.expand_path(__FILE__) %>
<br />
<br />
<form>
    I want to obtain the revenue data for the year
    <%= select_year(((params["date"] && params["date"]["year"]) || 2001).to_i,
        :start_year => 1992, :end_year => 2001) %>
    <input type="submit" value="OK">
</form>
</div>

<img src="<%= url_for(:action => 'getchart',
    :year => ((params["date"] && params["date"]["year"]) || 2001)) %>">

</body>
</html>

The default action for the controller "index" and the correspond view "index.rhtml" simply creates an HTML web page with a drop down list box to allow the user to select the year. The HTML web page also contains an <IMG> tag referencing the "getchart" action.

<img src="<%= url_for(:action => 'getchart',
    :year => ((params["date"] && params["date"]["year"]) || 2001)) %>">

The "getchart" action contains the code that actually creates the chart. The first part of the code are standard Ruby On Rails database code. It queries the database for using the selected year as a condition. A loop is then used to read the columns of the records into arrays.

#
# Query database for the selected year and read results into arrays
#

records = Revenue.find(:all, :conditions => ["Year(TimeStamp) = ?", selectedYear],
    :order => "TimeStamp")

software = []
hardware = []
services = []
records.each do |r|
    software.push(r.Software)
    hardware.push(r.Hardware)
    services.push(r.Services)
end

After we read the data into arrays, the second part of the code is to create a stacked bar chart using the given data. This is very similar to the examples in other parts of this documentation, so it will not be explained further.