Android – In MPAndroidChart Library, How to wrap X Axis Labels to two lines when long

androidmpandroidchart

I am trying to show X axis label to go to 2 lines when they are long. How to achieve this in LineChart? See screenshot below. I want time to go to second line instead of staying next to date

enter image description here

Best Answer

For those like me who want to achieve this but keep the original library, here is a simple solution inspired by @fgueli's modifications. This applies for one break line only (add "\n" in your labels) but you can easily adapt it to your needs.

  1. Subclass XAxisRenderer

    public class CustomXAxisRenderer extends XAxisRenderer {
        public CustomXAxisRenderer(ViewPortHandler viewPortHandler, XAxis xAxis, Transformer trans) {
             super(viewPortHandler, xAxis, trans);
        }
    
        @Override
        protected void drawLabel(Canvas c, String formattedLabel, float x, float y, MPPointF anchor, float angleDegrees) {
            String line[] = formattedLabel.split("\n");
            Utils.drawXAxisValue(c, line[0], x, y, mAxisLabelPaint, anchor, angleDegrees);
            Utils.drawXAxisValue(c, line[1], x + mAxisLabelPaint.getTextSize(), y + mAxisLabelPaint.getTextSize(), mAxisLabelPaint, anchor, angleDegrees);
        }
    }
    

  1. Set this renderer on the desired chart

    lineChart.setXAxisRenderer(new CustomXAxisRenderer(lineChart.getViewPortHandler(), lineChart.getXAxis(), lineChart.getTransformer(YAxis.AxisDependency.LEFT)));
    

  1. Enjoy!

LineChart labels on multiple lines

Related Topic