I'm using the MPAndroidChart library to create bar charts.
We can use the following to show the bar values on top of the bar.
mChart.setDrawValueAboveBar(false);
or we can use this :
barDataSet.setDrawValues(true);
to show the bar values inside the bar itself. I want to know if we can set a custom position for the values. For example below the y-axis.
Solution
public class TextBarChartRenderer extends BarChartRenderer {
public TextBarChartRenderer(BarDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler) {
super(chart, animator, viewPortHandler);
}
@Override
public void drawValues(Canvas c) {
List<IBarDataSet> dataSets = mChart.getBarData().getDataSets();
final float valueOffsetPlus = Utils.convertDpToPixel(22f)
float negOffset;
for (int i = 0; i < mChart.getBarData().getDataSetCount(); i++) {
IBarDataSet dataSet = dataSets.get(i);
applyValueTextStyle(dataSet);
float valueTextHeight = Utils.calcTextHeight(mValuePaint, "8");
negOffset = valueTextHeight + valueOffsetPlus;
BarBuffer buffer = mBarBuffers[i];
float left;
float right;
float top;
float bottom;
for (int j = 0; j < buffer.buffer.length * mAnimator.getPhaseX(); j += 4) {
left = buffer.buffer[j];
right = buffer.buffer[j + 2];
top = buffer.buffer[j + 1];
bottom = buffer.buffer[j + 3];
float x = (left + right) / 2f;
if (!mViewPortHandler.isInBoundsRight(x))
break;
if (!mViewPortHandler.isInBoundsY(top) || !mViewPortHandler.isInBoundsLeft(x))
continue;
BarEntry entry = dataSet.getEntryForIndex(j / 4);
float val = entry.getY();
if(val > 0) {
drawValue(c, dataSet.getValueFormatter(), val, entry, i, x,
(bottom + negOffset),
dataSet.getValueTextColor(j / 4));
}
}
}
}
}
Also had to add this so that the values are visible
mChart.setExtraOffsets(0, 0, 0, 20);