Search code examples
androidgraphandroid-graphviewmpandroidchart

Can't optimize line chart using MPAndroidChart library


I am trying to make a good looking line chart iwht MPAndroidChart, but I am having some problems. Here is what I got now enter image description here

and here is the code for it

public void createGraph() {
    chart.setTouchEnabled(false);
    chart.setDragEnabled(false);
    chart.setHighlightEnabled(false);
    chart.setDrawYLabels(true);
    chart.setDrawXLabels(true);
    chart.animateXY(2000, 2000);
    chart.setDrawBorder(true);
    chart.setPadding(30, 30, 30, 30);
    setData();
}

private void setData() {
    String[] stages = { "Stage1", "Stage2", "Stage3", "Stage4" };
    ArrayList<Entry> yVals = new ArrayList<Entry>();
    yVals.add(new Entry(0.0f, 0));
    yVals.add(new Entry(Float.parseFloat(nicotineTwo), 1));
    yVals.add(new Entry(Float.parseFloat(nicotineThree), 2));
    yVals.add(new Entry(Float.parseFloat(nicotineFour), 3));
    LineDataSet set1 = new LineDataSet(yVals, "");
    set1.setColor(Color.BLACK);
    set1.setCircleColor(Color.BLACK);
    set1.setLineWidth(1f);
    ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
    dataSets.add(set1);
    LineData data = new LineData(stages, dataSets);
    chart.setData(data);
}

What I need is:

  1. Remove that black box under the lower left corner
  2. Make the text "Nicotine Lowered" somewhat bigger and more readable
  3. Add some padding or something, because the Stage4 at the top right is out of the screen
  4. Make the numbers along the line bigger and if possible with percents "25.0%"
  5. Hide the first value on the line, since it will always be 0
  6. Show all the scale values on the Y scale, from 0 to 100 (right now there is no 100)

Please help me, this library is realy confusing me


Solution

    1. The "black-box" is the legend. Call chart.getLegend().setEnabled(false) to disable it.
    2. That is the "description-text". Call chart.setDescriptionTextSize(...) to customize its size.
    3. There are two possible solutions. You can either add more margin via .xml, or call

      XAxis x = chart.getXAxis();
      x.setAvoidFirstLastClipping(true);
      
    4. For increasing the value text size, call data.setValueTextSize(...). For customly formatting values inside the chart, check out the ValueFormatter interface the library provides.
    5. Can also be solved with the ValueFormatter interface. e.g. if(value == 0) return "";
    6. Right now the range of values on the y-axis is automatically determined by the chart. You can set a fixed range of values by calling yAxis.setAxisMaxValue(...) & yAxis.setAxisMinValue(...).

    Here is the full documentation.