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
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.
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);
}
}
Set this renderer on the desired chart
lineChart.setXAxisRenderer(new CustomXAxisRenderer(lineChart.getViewPortHandler(), lineChart.getXAxis(), lineChart.getTransformer(YAxis.AxisDependency.LEFT)));
I modified the library to allow multiline label on the xAxis using \n
https://github.com/fabriziogueli/MPAndroidChart/tree/axis_multiline_labels
It is working right now but need further testing and maybe some code styling / adjustment.
XAxis xAxis = mChart.getXAxis();
xAxis.setMultiLineLabel(true);
Then you can use for example a SimpleDateFormat like this:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy\nHH:mm a");
Maybe you have to set extra bottom offset to your chart:
mChart.setExtraBottomOffset(50);
Improved version of @Guillaume Jounel's answer to support multiple newlines, as well as strings w/o a newline.
@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);
for (int i = 1; i < line.length; i++) { // we've already processed 1st line
Utils.drawXAxisValue(c, line[i], x, y + mAxisLabelPaint.getTextSize() * i,
mAxisLabelPaint, anchor, angleDegrees);
}
}
This looks like something that you will have to implement yourself by modifying the library to your needs.
It is currently not possible by default to have multiple lines on the x-axis. The reason therefore is that Android Canvas
cannot simply plot a string e.g. like this "Line 1\nLine2"
as two lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With