Search code examples
androidchartslabelmpandroidchartlinechart

MPAndroidChart line chart label attached to the line


I want to achieve an effect similar to this using the MPAndroidChart library enter image description here

I want my label to be attached to the Chart line or at least be close to it. Is something like this possible using this library? Or is there a walkaround for this? Something that will have a similar result


Solution

  • A possible way is to use the marker, chart.setMarker(), but marker only shows when user tap on the chart, if you want the marker to show constantly, an custom chart can be invoked and override the function drawMarkers like this, the marker is drawn in the middle of chart:

    @Override protected void drawMarkers(Canvas canvas) {
        int j = 0;
        IDataSet set = mData.getDataSetByIndex(j);
        int i = set.getEntryCount() / 3;
        Entry e = set.getEntryForIndex(i);
        Highlight highlight = new Highlight(e.getX(), e.getY(), i);
        highlight.setDataIndex(j);
        // callbacks to update the content
        mMarker.refreshContent(e, highlight);
        MPPointD pix = getTransformer(set.getAxisDependency()).getPixelForValues(e.getX(), e.getY());
        highlight.setDraw((float)pix.x, (float)pix.y);
        // draw the marker
        float[] pos = getMarkerPosition(highlight);
        mMarker.draw(canvas, pos[0], pos[1]);
    }
    

    Picture as below, the yellow tag is the marker, it is displayed constantly and without a user tap: enter image description here

    ----Updated July 5th

    In the demo LineChartActivity1(https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartExample/src/main/java/com/xxmassdeveloper/mpchartexample/LineChartActivity1.java), line 98, chart.setMarker(mv); sets the Marker, and it allocated by new an MyMarkerView. The drawMarkers can be added at https://github.com/PhilJay/MPAndroidChart/blob/master/MPChartLib/src/main/java/com/github/mikephil/charting/charts/LineChart.java, but it's better to use a customed Chart extends from LineChart