Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - How to implement the Line Graph using Achartengine

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

like image 540
naresh Avatar asked Dec 12 '22 08:12

naresh


1 Answers


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.

like image 200
Aneesh Garg Avatar answered Mar 03 '23 09:03

Aneesh Garg