J4L RCHART, User Guide

Copyright 2012, J4L Components (http://www.java4less.com)
Go bak to contents


The Chart API

 

 

Chart creation process

We recommend you to create charts using the parameters provided by RChart Visual Builder (see ChartLoader in next section), however if you need it you can create charts using the Java API.

The process is:

1. Import RChart package import com.java4less.rchart.*;
import com.java4less.rchart.gc.*;
2. Create the title Title title=new Title("Sales (thousands $)")
3. Create the axis you need (depends on the chart, for example piecharts do not have axis) com.java4less.rchart.Axis XAxis=new Axis(Axis.HORIZONTAL,new Scale());
com.java4less.rchart.Axis YAxis=new Axis(Axis.VERTICAL,new Scale());
XAxis.scale.min=0;
YAxis.scale.min=0;
.....
4. Create the legend Legend l=new Legend();
l.addItem("Products",new FillStyle( GraphicsProvider.getColor(ChartColor.BLUE)) ));
l.addItem("Services",new FillStyle( GraphicsProvider.getColor(ChartColor.GREEN)) ));
5. Create the axis labels

XLabel= new HAxisLabel("", GraphicsProvider.getColor(ChartColor.BLUE)), GraphicsProvider.getFont("Arial",ChartFont.BOLD,14));

YLabel= new VAxisLabel("Brutto", GraphicsProvider.getColor(ChartColor.BLACK)),new GraphicsProvider.getFont("Arial",ChartFont.BOLD,14));

6. create the plotter (or plotters if you combine lines and bars) LinePlotter3D plot=new LinePlotter3D();
7. create the chart and set properties (labels,legend) com.java4less.rchart.Chart chart=new Chart(title,plot,XAxis,YAxis);
chart.XLabel=XLabel;
chart.YLabel=YLabel;
chart.legend=l;
8. create the data series double[] d1={1,1,3,3.5,5,4,2};
LineDataSerie data1= new LineDataSerie(d1,new LineStyle(0.2f, GraphicsProvider.getColor(ChartColor.BLUE)) ,LineStyle.LINE_NORMAL));
9. add serie to chart chart.addSerie(data1);
   

 

 

The ChartLoader

You can use the chart loader to create the charts using the parameters created by RChart Visual Builder in this way. This approach is easier to learn, to use (since you can use the Visual Builder) and less error prone. The following code shows how to use the ChartLoader class:

import com.java4less.rchart.*;

...

ChartLoader loader=new ChartLoader();
// Set parameters
loader.setParameter("TITLECHART","Sales 1999");
loader.setParameter("LEGEND_FILL","WHITE");
loader.setParameter("LEGEND_VERTICAL","FALSE");
loader.setParameter("LEGEND_BORDER","0.2|0x0|NORMAL");
loader.setParameter("SERIE_1","Pie");
loader.setParameter("SERIE_TYPE_1","PIE");
loader.setParameter("SERIE_FONT_1","ARIAL|BOLD|12");
loader.setParameter("SERIE_DATA_1","94|48|28");
loader.setParameter("PIE_NAME_1","Products");
loader.setParameter("PIE_NAME_2","Services");
loader.setParameter("PIE_NAME_3","Other");
loader.setParameter("PIE_STYLE_1","RED");
loader.setParameter("PIE_STYLE_2","BLUE");
loader.setParameter("PIE_STYLE_3","GREEN");
loader.setParameter("PIECHART_3D","true");
loader.setParameter("PIE_LABEL_FORMAT","#VALUE# (#PERCENTAGE#)");
loader.setParameter("SERIE_LABELS_1","Products|Services|Other");
loader.setParameter("SERIE_TOGETHER_1","true|false|true");
loader.setParameter("LEGEND_POSITION","TOP");
loader.setParameter("LEGEND_MARGIN","0.3");
loader.setParameter("CHART_BORDER","0.2|0x0|NORMAL");
loader.setParameter("CHART_FILL","0x99cccc");

/* process parameters and create chart*/
Chart chart=loader.buildChart(false,false);
chart.setWidth(300);
chart.setHeight(300);

/* create png file  or use chart object in the ChartPanel */
chart.saveToFile(new FileOutputStream("chart.png"),"PNG");
}

catch(Exception e) {
System.err.println("Error: " + e.getMessage());
}



Please see also our sample application com.java4less.rchart.samples.ShowCharts.java.


You can also read the parameters directly from a file:

import com.java4less.rchart.*;

...

ChartLoader loader=new ChartLoader();
// Set parameters
loader.setDataFile("examples\\piechart3D.txt"); // this can also be a url like http://www.myserver.com or file:///....

/** loading the chart parameters from the application assets

InputStream is = getAssets().open("mychart.txt"); 
loader.loadFromFile(is, true); 

*/

/* process parameters and create chart*/
Chart chart=loader.buildChart(false,true); // true means read data file
chart.setWidth(300);
chart.setHeight(300);

/* create png file or use chart object in the ChartPanel*/
chart.saveToFile(new FileOutputStream("chart.png"),"PNG");

}

catch(Exception e) {
System.err.println("Error: " + e.getMessage());
}

 

In all cases the steps are:

  1. Create the chart loader
  2. Set the parameters or load them from file
  3. build the chart
  4. export the chart to an image file or display it using a ChartPanel View (see next sections)

 

Displaying the chart (ChartPanel view)

RChart includes ready to use class for displaying charts in Android applications. The class com.java4less.rchart.android.ChartPanel is an Android view.

Our demo application
com.java4less.rchart.samples.ShowCharts.java shows how to use the class. The following code shows how to use the ChartPanel:

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    cha=new ChartLoader();
    // this is to be able to load the images
    ChartAndroidImage.assets=getAssets();

    String chartfile=this.getIntent().getStringExtra("com.java4less.rchart.samples.file");
    super.onCreate(icicle);

    chartPanel = new ChartPanel(this);  // step 1

    try {
        chartPanel.setChart(loadFromAsset(chartfile));  // step 2
        //chartPanel.setChart(this.createDefaultChart());
    } catch (Exception e) {
    Log.e(ChartPanel.TAG,"Could not lod chart from file.",e);
    }

    setContentView(chartPanel);  // step 3
}

The key steps have been highlighted in red:

  1. first you create the ChartPanel
  2. then you create a Chart object and pass it to the ChartPanel
  3. finally you set the content view of your Android activity

The ChartPanel will display the chart and also will take care of capturing the move event for implementing scrolling, in case you have activated it.

Exporting the chart to png , jpg or webp

RChart can create the following image files:  PNG, JPG and WEBP. This can be done by executing chart.saveToFile(outputstream,format), where format can be  "PNG", "WEBP" of "JPG".


Updating the chart and realtime updates

There is a way to force RChart to rebuild itself every X seconds. In this way you can create charts that will get updated with realtime data. For example you can let RChart read new data from a given URL or file every 5 seconds. Look at the same application provided (com.java4less.rchart.samples.ShowCharts.java ) with the product to see a complete working example.

  1. First of all you need to implement a ChartAdapter class and catch the BEFORE_UPDATE event.In this example the createRealtimeData() method is changing the values in the chart.

    ChartAdapter chartAdapterRealtime=new ChartAdapter() {
        public void chartEvent(Chart c,int type) {
        Log.e(ChartPanel.TAG,"Chart event "+ type); 
        // load new chart
        if (type==ChartListener.EVENT_BEFORE_UPDATE) createRealtimedata(cha);
        }
    };
  2.  Add the chart adapter to the chart as listener, in order to receive the events:

    chart.addChartListener(chartAdapterRealtime)
  3. Activate the chart update:

    chart.msecs=2000; // update every 2 seconds
    chart.startUpdater();  // use chart.stopUpdater() to stop the update thread



Each time the chart gets updated by the updater thread, RChart will trigger 2 events which can be catched by ChartListeners. These events are:

There are 2 ways for updating the values in your chart (normally inside the EVENT_BEFORE_UPDATE event handler):

  1. If you have used the ChartLoader to create your chart you can rebuild the same Chart object after you have changed some of the parameters. For example:


    // set new parameters, for example update values in serie 1
    myChart.loader.setParameter("SERIE_DATA_1","10|20|30 ....");

    // rebuild chart
    // this is not required inside the EVENT_BEFORE_UPDATE event handler

    myChart.loader.build(myChart,false,false); // since we pass the chart as first parameter, the loader will not create a new Chart object but it will rebuild the existing one


    Note: if you are setting the new parameters inside the EVENT_BEFORE_UPDATE event, you should not rebuild the chart yourself, instead you must set:

    myChart.autoRebuild=true;

    and the chart will be rebuilt automatically.

  2. Or you can use the Java API to change the values in the chart. There are 2 methods specifically designed for this:

    - Plotter.replaceSerie();
    - DataSerie.replaceYvalueAt();

    You can change a given value in the data series using the following code:

    myChart.plotters[0].getSerie(0).replaceYValueAt(1,newValue); // replace second value in serie 0

    or you can replace the whole series:


    myChart.plotters[0].replaceSerie(0,yourDataSerie);

    the first 0 means you want to replace a serie in Plotter 0 (normally you only have 1 plotter). The second 0 means you want to replace the first serie in the given plotter.

    Note: if you are changing the chart inside the EVENT_BEFORE_UPDATE event, you should disable the automatic chart rebuild with:

    myChart.autoRebuild=false;

    otherwise RChart would rebuild the chart using the original ChartLoader's parameters and your changes would be overwritten.

    We only recomment to use the Java API if you are going to update values, not change the number of values to plot. In the second case you may need to update the scale or the labels and would be easier rebuilding the whole chart.