Home » Android » android – How to remove padding from horizontal barchart of mpandroidchart?

android – How to remove padding from horizontal barchart of mpandroidchart?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to make a horizontal barchart that covers the entire parent layout but its not. Below is my code –

HorizontalBarChart barchart = new HorizontalBarChart(activity);
barchart.setLayoutParams(new LinearLayout.LayoutParams(0, 110, weight));

ArrayList<BarEntry> entries = new ArrayList<BarEntry>();
entries.add(new BarEntry(86.0f, 0));

BarDataSet dataset = new BarDataSet(entries, "");
dataset.setColor(Color.parseColor("#E0E0E0"));

ArrayList<String> labels = new ArrayList<String>();
labels.add("86.0"); 

BarData bardata = new BarData(labels, dataset);
barchart.setData(bardata);
barchart.setDescription("");

Legend legend = barchart.getLegend();
legend.setEnabled(false);

YAxis topAxis = barchart.getAxisLeft();
topAxis.setDrawLabels(false);

YAxis bottomAxis = barchart.getAxisRight();
bottomAxis.setDrawLabels(false);

XAxis rightAxis = barchart.getXAxis();
rightAxis.setDrawLabels(false);
bottomAxis.setDrawLabels(false);

barchart.setPadding(-1, -1, -1, -1);
barchart.setBackgroundColor(Color.CYAN);

return barchart;

I want my horizontal barchart (barchart) to fill the entire blue area. Can someone please help.

EDIT : @PhilippJahoda i tried your solution, but at first launch it shows up the same way it was, when i click/touch the chart then only it covers the entire area. Can you please tell me why i have to touch the chart to make it fill the entire space.

At first launch it looks like –

Screen shot: enter image description here

After clicking it looks like –

Screen shot2: enter image description here

How to&Answers:

Update to the latest version of the library if you have not already.
Then, just remove all offsets from the chart. It’s in the documentation.

Call:

chart.setViewPortOffsets(0f, 0f, 0f, 0f);

Answer:

The padding removal works with

chart.setViewPortOffsets(0f, 0f, 0f, 0f);

but if the effect appears only after touch, try to invalidate chart view (after you set data) this way:

post(new Runnable() {
    @Override
    public void run() {
        chartView.invalidate();
    }
});

Answer:

    YAxis yl = chart.getAxisLeft();
    yl.setSpaceTop(20f);

Answer:

Best way to control the padding what I feel is as:

  1. Set all the offsets to 0

    chart.setViewPortOffsets(0f, 0f, 0f, 0f);

  2. Control the padding from the XML

    com.github.mikephil.charting.charts.LineChart
    android:id=”@+id/chart”
    android:layout_width=”match_parent”
    android:layout_height=”500dp”
    android:layout_marginTop=”10dp”
    android:layout_marginLeft=”10dp”
    android:layout_marginBottom=”10dp”