android - How to implement the Line Graph using Achartengine

naresh picture naresh · Oct 7, 2011 · Viewed 7.4k times · Source

I am new to Graph concept in android. In my app i want implement the line graph using achartengine. I have the demo of achartengine it consists a lot of code. I am not able to understand the line graph. I want simple Line graph using achartengine. Please can anybody help me.

thanks

Answer

Aneesh Garg picture Aneesh Garg · Dec 19, 2011


Following method will generate random points (x,y) and add it to XYSeries (it is series of points to be plotted on chart).

private XYMultipleSeriesDataset getDemoDataset() {
    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    final int nr = 7;
    Random r = new Random();
    for (int i = 0; i < SERIES_NR; i++) {
        XYSeries series = new XYSeries("Demo series " + (i + 1));
        for (int k = 0; k < nr; k++) {
            series.add(k, 20 + r.nextInt() % 100);
        }
        dataset.addSeries(series);
    }
    return dataset;
}

Following Method will return a multiple renderer which is used to draw line charts.

private XYMultipleSeriesRenderer getDemoRenderer() {
    XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
    renderer.setAxisTitleTextSize(12);
    renderer.setChartTitleTextSize(12);
    renderer.setLabelsTextSize(15);
    renderer.setLegendTextSize(15);
    renderer.setPointSize(5f);
    renderer.setMargins(new int[] { 20, 30, 15, 0 });
    XYSeriesRenderer r = new XYSeriesRenderer();
    r.setColor(Color.BLACK);
    r.setPointStyle(PointStyle.CIRCLE);
    r.setFillBelowLine(false);
    r.setFillPoints(true);
    renderer.addSeriesRenderer(r);
    setChartSettings(renderer);
    return renderer;
}

Following method will set the settings for your chart. You can look for more options in docs provided by AChartEngine.

private void setChartSettings(XYMultipleSeriesRenderer renderer) {
    renderer.setChartTitle("Chart demo");
    renderer.setXTitle("x values");
    renderer.setYTitle("y values");
    renderer.setApplyBackgroundColor(false);
    renderer.setRange(new double[] {0,6,-70,40});
    renderer.setFitLegend(false);
    renderer.setAxesColor(Color.BLACK);
    renderer.setShowGrid(true);
    renderer.setXAxisMin(0.5);
    renderer.setXAxisMax(10.5);
    renderer.setYAxisMin(0);
    renderer.setZoomEnabled(false);
    renderer.setYAxisMax(30);
  }

You can now get the line chart in two ways:

  • Chart as a view which can be added to any layout:

    ChartFactory.getLineChartView(this, getDemoDataset(), getDemoRenderer());

  • Chart as an Intent for a new activity alltogether

    ChartFactory.getLineChartIntent(this, getDemoDataset(), getDemoRenderer());

PS: SERIES_NR is a constant which tells how many line series you want to draw.