Plot Multiple Charts in one in MPAndroidChart

VenomVendor picture VenomVendor · Nov 11, 2014 · Viewed 17.3k times · Source

I have to plot two different dataSets in a single graph.

DataSet-1

    String[] xAxisOne = new String[] {
            "0", "1", "2", "3", "4", "5", "6"
    };

    float[] dataInput = {
            1f, 2f, 3f, 4f, 5f, 6f, 7f
    };

DataSet-2

    String[] xAxisTwo = new String[] {
            "0", "2", "4", "5", "6", "8", "9"
    };

    float[] dataIn = {
            3f, 4f, 5f, 6f, 7f, 8f, 9f
    };

In the above data, DataSet-1 is reference by which graph is created. DataSet-2 has to be plotted in the same with different set of X-Values {xAxisTwo}.

In existing Implementation, first 6 values {dataInput} are plotted & next 6 values {dataIn} are plotted with reference to xAxisOne, How to plot as required.

Answer

Guilherme Muniz picture Guilherme Muniz · Aug 7, 2015

You can do this with LineChart and unifying the xAxis and ignoring the "null" point for each dataset. See the code below:

//float[] dataInput = {
//      1f, 2f, 3f, 4f, 5f, 6f, 7f
//};

//values for datainput Dataset1 at your axisone positions
ArrayList<Entry> dataset1 = new ArrayList<Entry>();
dataset1.add(new Entry(1f, 0));
dataset1.add(new Entry(2f, 1));
dataset1.add(new Entry(3f, 2));
dataset1.add(new Entry(4f, 3));
dataset1.add(new Entry(5f, 4));
dataset1.add(new Entry(6f, 5));
dataset1.add(new Entry(7f, 6));

//float[] dataIn = {
//      3f, 4f, 5f, 6f, 7f, 8f, 9f
//};

//values for datainput Dataset2 at your axisone positions
ArrayList<Entry> dataset2 = new ArrayList<Entry>();
dataset2.add(new Entry(3f, 0));
dataset2.add(new Entry(4f, 2));
dataset2.add(new Entry(5f, 4));
dataset2.add(new Entry(6f, 5));
dataset2.add(new Entry(7f, 6));
dataset2.add(new Entry(8f, 7));
dataset2.add(new Entry(9f, 8));

//String[] xAxisOne = new String[] {
//      "0", "1", "2", "3", "4", "5", "6"
//};

///String[] xAxisTwo = new String[] {
///     "0", "2", "4", "5", "6", "8", "9"
///};


// Union from xAxisOne and xAxisTwo
String[] xAxis = new String[] {"0", "1", "2", "3", "4", "5", "6", "8", "9"};


ArrayList<LineDataSet> lines = new ArrayList<LineDataSet> ();

LineDataSet lDataSet1 = new LineDataSet(dataset1, "DataSet1");
lDataSet1.setColor(Color.RED);
lDataSet1.setCircleColor(Color.RED);
lines.add(lDataSet1);
lines.add(new LineDataSet(dataset2, "DataSet2"));

LineChart chart = (LineChart) getView().findViewById(R.id.chart);
chart.setData(new LineData(xAxis, lines));

The final result will be:

Final chart

Looks that the red line of dataset1 have 2 more points than blue line. If the dataset1 have only these two points(at position 1 and 3) like this:

ArrayList<Entry> dataset1 = new ArrayList<Entry>();
    dataset1.add(new Entry(2f, 1));
    dataset1.add(new Entry(4f, 3));

it will be the result:

enter image description here