Skip to content Skip to sidebar Skip to footer

How To Create A Barchart With Grouped Bars With Mpandroidchart?

How can i compare two set of data using BarChart of MPAndroidChart. It should look like this image below: I edited a code, I get from a sample project in github. how can I put tog

Solution 1:

Since there has been an update on BarData constructor you need to use following code:

BarChartbarChart= (BarChart) view.findViewById(R.id.chart);
barChart.setDrawBarShadow(false);
barChart.setDrawValueAboveBar(true);
barChart.setDescription("");
barChart.setMaxVisibleValueCount(50);
barChart.setPinchZoom(false);
barChart.setDrawGridBackground(false);

XAxisxl= barChart.getXAxis();
xl.setGranularity(1f);
xl.setCenterAxisLabels(true);
xl.setValueFormatter(newAxisValueFormatter() {
    @Overridepublic String getFormattedValue(float value, AxisBase axis) {
        return String.valueOf((int) value);
    }

    @OverridepublicintgetDecimalDigits() {
        return0;
    }
});

YAxisleftAxis= barChart.getAxisLeft();
leftAxis.setValueFormatter(newAxisValueFormatter() {
    @Overridepublic String getFormattedValue(float value, AxisBase axis) {
        return String.valueOf((int) value);
    }

    @OverridepublicintgetDecimalDigits() {
        return0;
    }
});
leftAxis.setDrawGridLines(false);
leftAxis.setSpaceTop(30f);
leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true
barChart.getAxisRight().setEnabled(false);

//datafloatgroupSpace=0.04f;
floatbarSpace=0.02f; // x2 datasetfloatbarWidth=0.46f; // x2 dataset// (0.46 + 0.02) * 2 + 0.04 = 1.00 -> interval per "group"intstartYear=1980;
intendYear=1985;
List<BarEntry> yVals1 = newArrayList<BarEntry>(); 
List<BarEntry> yVals2 = newArrayList<BarEntry>();

for (inti= startYear; i < endYear; i++) {
    yVals1.add(newBarEntry(i, 0.4f));
    yVals2.add(newBarEntry(i, 0.7f));
}

BarDataSet set1, set2;
if (barChart.getData() != null && barChart.getData().getDataSetCount() > 0) {
    set1 = (BarDataSet)barChart.getData().getDataSetByIndex(0);
    set2 = (BarDataSet)barChart.getData().getDataSetByIndex(1);
    set1.setValues(yVals1);
    set2.setValues(yVals2);
    barChart.getData().notifyDataChanged();
    barChart.notifyDataSetChanged();
} else {
    // create 2 datasets with different types
    set1 = newBarDataSet(yVals1, "Company A");
    set1.setColor(Color.rgb(104, 241, 175));
    set2 = newBarDataSet(yVals2, "Company B");
    set2.setColor(Color.rgb(164, 228, 251));
    ArrayList<IBarDataSet> dataSets = newArrayList<IBarDataSet>();
    dataSets.add(set1);
    dataSets.add(set2);
    BarDatadata=newBarData(dataSets);
    barChart.setData(data);
}

barChart.getBarData().setBarWidth(barWidth);
barChart.getXAxis().setAxisMinValue(startYear);
barChart.groupBars(startYear, groupSpace, barSpace);
barChart.invalidate();

That's how it will look like:

Result

Solution 2:

Yes, that can be done quite easily.

What you need is a BarChart with multiple BarDataSets where each set (in your case) represents one sex (men or women).

Example code (without realm.io)

    List<String> xValues = ...; // "Denmark", "Finland", ...XAxisxAxis= chart.getXAxis();
    xAxis.setValueFormatter(newMyValueFormatter(xValues));

    // create 2 datasets BarDataSetset1=newBarDataSet(valuesMen, "Men");
    set1.setColor(Color.BLUE);
    BarDataSetset2=newBarDataSet(valuesWomen, "Women");
    set2.setColor(Color.RED);

    BarDatadata=newBarData(set1, set2);
    chart.setData(data);
    chart.groupBars(...); // available since release v3.0.0
    chart.invalidate(); // refresh

If you need further assistance, here is a detailed tutorial on grouped BarChart available on the wiki.

If you want to "stack" values in a BarChart above each other, you need to create a stacked-barchart: Android Stacked Bars Chart

Solution 3:

Most of the answers I tried either have issues like misaligned, non centered labels or bars getting hidden out of screen space. So after bit of attempts I have a proper working poc.

Last 4 lines are the most important.

    ArrayList<BarEntry> barEntries = newArrayList<>();
    ArrayList<BarEntry> barEntries1 = newArrayList<>();
    ArrayList<BarEntry> barEntries2 = newArrayList<>();
    ArrayList<BarEntry> barEntries3 = newArrayList<>();

    barEntries.add(newBarEntry(1,989.21f));
    barEntries.add(newBarEntry(2,420.22f));
    barEntries.add(newBarEntry(3,758));
    barEntries.add(newBarEntry(4,3078.97f));
    barEntries.add(newBarEntry(5,14586.96f));
    barEntries.add(newBarEntry(6,400.4f));
    barEntries.add(newBarEntry(7,5888.58f));

    barEntries1.add(newBarEntry(1,950));
    barEntries1.add(newBarEntry(2,791));
    barEntries1.add(newBarEntry(3,630));
    barEntries1.add(newBarEntry(4,782));
    barEntries1.add(newBarEntry(5,2714.54f));
    barEntries1.add(newBarEntry(6,500));
    barEntries1.add(newBarEntry(7,2173.36f));

    barEntries2.add(newBarEntry(1,900));
    barEntries2.add(newBarEntry(2,691));
    barEntries2.add(newBarEntry(3,1030));
    barEntries2.add(newBarEntry(4,382));
    barEntries2.add(newBarEntry(5,2714f));
    barEntries2.add(newBarEntry(6,5000));
    barEntries2.add(newBarEntry(7,1173f));

    barEntries3.add(newBarEntry(1,200));
    barEntries3.add(newBarEntry(2,991));
    barEntries3.add(newBarEntry(3,1830));
    barEntries3.add(newBarEntry(4,3082));
    barEntries3.add(newBarEntry(5,214));
    barEntries3.add(newBarEntry(6,5600));
    barEntries3.add(newBarEntry(7,9173));

    BarDataSetbarDataSet=newBarDataSet(barEntries,"DATA SET 1");
    barDataSet.setColor(Color.parseColor("#F44336"));
    BarDataSetbarDataSet1=newBarDataSet(barEntries1,"DATA SET 2");
    barDataSet1.setColors(Color.parseColor("#9C27B0"));
    BarDataSetbarDataSet2=newBarDataSet(barEntries2,"DATA SET 3");
    barDataSet1.setColors(Color.parseColor("#e241f4"));
    BarDataSetbarDataSet3=newBarDataSet(barEntries3,"DATA SET 4");
    barDataSet1.setColors(Color.parseColor("#42f46e"));

    String[] months = newString[] {"TYPE 1", "TYPE 2", "TYPE 3", "TYPE 4"};
    BarDatadata=newBarData(barDataSet,barDataSet1,barDataSet2,barDataSet3);
    barChart.setData(data);

    XAxisxAxis= barChart.getXAxis();
    xAxis.setValueFormatter(newIndexAxisValueFormatter(months));
    barChart.getAxisLeft().setAxisMinimum(0);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setGranularity(1);
    xAxis.setCenterAxisLabels(true);
    xAxis.setGranularityEnabled(true);

    floatbarSpace=0.02f;
    floatgroupSpace=0.3f;
    intgroupCount=4;

    //IMPORTANT *****
    data.setBarWidth(0.15f);
    barChart.getXAxis().setAxisMinimum(0);
    barChart.getXAxis().setAxisMaximum(0 + barChart.getBarData().getGroupWidth(groupSpace, barSpace) * groupCount);
    barChart.groupBars(0, groupSpace, barSpace); // perform the "explicit" grouping//***** IMPORTANT

and the end result I got is:

Bar graph with labels fixed

Solution 4:

  • Step1 Divide first number of groups in bar chart. Like below sample code displaying for 5 groups. Every group have 5 bars in that.

               xaxis0 = new ArrayList<>();
               for (int i = 0; i < cData.size(); i++) {
    
                   String str = cData.get(i).get("count");
                   str = str.replaceAll("\\[", "").replaceAll("\\]", "");
                   String[] finalString = str.split(",");
                   if (i == 0) {
                       for (int k = 0; k < finalString.length; k++) {
    
                           int data22 = Integer.parseInt(finalString[k]);
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet1.add(v1e1);
                       }
                   }
                   if (i == 1) {
                       for (int k = 0; k < finalString.length; k++) {
                           int data22 = Integer.parseInt(finalString[k] + "");
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet2.add(v1e1);
                       }
                   }
                   if (i == 2) {
                       for (int k = 0; k < finalString.length; k++) {
                           int data22 = Integer.parseInt(finalString[k] + "");
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet3.add(v1e1);
                       }
                   }
                   if (i == 3) {
                       for (int k = 0; k < finalString.length; k++) {
                           int data22 = Integer.parseInt(finalString[k] + "");
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet4.add(v1e1);
                       }
                   }
                   if (i == 4) {
                       for (int k = 0; k < finalString.length; k++) {
                           int data22 = Integer.parseInt(finalString[k] + "");
                           BarEntry v1e1 = new BarEntry(data22, position);
                           valueSet5.add(v1e1);
                       }
                   }
                   xaxis0.add(i, xdata.get(i).get("date"));
    
  • Step2 In above code you observe that 5 groups of bar entry loading data in loop of every valueset - ArrayList valueSet2 = new ArrayList<>(); Initialize before this valuesets and

  • Step3 And load that 5 sets to Bardataset like below

    ` BarDataSet barDataSet1 = new BarDataSet(valueSet1, "Set1"); barDataSet1.setColors(whitecolors); barDataSet1.setValueTextColor(Color.WHITE);

    BarDataSet barDataSet2 = new BarDataSet(valueSet2, "Set2"); barDataSet2.setColors(whitecolors); barDataSet2.setValueTextColor(Color.WHITE);

    BarDataSet barDataSet3 = new BarDataSet(valueSet3, "Set3"); barDataSet3.setColors(whitecolors);

    barDataSet3.setValueTextColor(Color.WHITE); BarDataSet barDataSet4 = new BarDataSet(valueSet4, "Set4");

    barDataSet4.setColors(whitecolors); barDataSet4.setValueTextColor(Color.WHITE);

    BarDataSet barDataSet5 = new BarDataSet(valueSet5, "Set5"); barDataSet5.setColors(whitecolors);

    barDataSet5.setValueTextColor(Color.WHITE); dataSets = new ArrayList<>(); dataSets.add(barDataSet1); dataSets.add(barDataSet2); dataSets.add(barDataSet3); dataSets.add(barDataSet4); dataSets.add(barDataSet5); `

  • Last step need to attached this data to Bardata like below code

BarData data11 = new BarData(xaxis0, dataSets); data11.setGroupSpace(100f);

               holder.chart.setData(data11);
               XAxis xAxis = holder.chart.getXAxis();
               xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
               xAxis.setDrawGridLines(true);  

xAxis.setGridColor(context.getResources().getColor(R.color.white));

               xAxis.isDrawLabelsEnabled();    

xAxis.setAxisLineColor(context.getResources().getColor(R.color.accentColor)); xAxis.setTextColor(context.getResources().getColor(R.color.white));

               xAxis.isAdjustXLabelsEnabled();

               xAxis.setAdjustXLabels(true);

               holder.chart.setDescription("");

               holder.chart.animateXY(2000, 2000);
 holder.chart.getAxisLeft().setTextColor(context.getResources().getColor(R.color.white));
               holder.chart.getAxisRight().setTextColor(context.getResources().getColor(R.color.white));
               holder.chart.setDrawGridBackground(false);
               holder.chart.getAxisRight().setEnabled(false);
               holder.chart.setDrawValueAboveBar(true);
               holder.chart.getAxisLeft().setEnabled(false);
               holder.chart.setSoundEffectsEnabled(true);
               holder.chart.getXAxis().setDrawGridLines(false);
               holder.chart.setTransitionGroup(true);
               YAxis yAxis = holder.chart.getAxisLeft();
               yAxis.setDrawGridLines(false);
               yAxis.setLabelCount(5);
               yAxis = holder.chart.getAxisRight();
               yAxis.setDrawGridLines(false);
               yAxis.setTextColor(context.getResources().getColor(R.color.white));
               Legend l =  holder.chart.getLegend();
               l.setEnabled(false);     
               Paint p = holder.chart.getPaint(Chart.PAINT_INFO);
               p.setTextSize(10);
               p.setColor(context.getResources().getColor(R.color.white));
               p.setTypeface(gotham);
               holder.chart.invalidate();
               l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
               l.setTextSize(200);
               yAxis.setValueFormatter(new LargeValueFormatter());

   # Thats it if you have doubt about this code ask me any time .......

Post a Comment for "How To Create A Barchart With Grouped Bars With Mpandroidchart?"