MPAndroidChart
MPAndroidChart copied to clipboard
Datapoint Index in Marker
I'm trying to implement the deletion of data points. The user touches a data point and the marker appears and includes a delete button. However, for this to work, I need the data point index so that I know which data point to delete. The Highlight class contains a dataset index and a data index, but no data point index.
Can you give more details with some example of code like what you have done so far to achieve it.
By having dataset Index, we can remove and pass the values to the chart again to redraw the graph, make sure you are calling notifyDataSetChanged() except for Pie Chart.
The issue is that there is no way directly to tell the index of the datapoint that was clicked, so instead I have to loop through all of the datapoints in that dataset index and try to match the values to the datapoint that was clicked. Here is an example for a time-based line graph:
public String onTooltipRefresh(final int datasetIndex, final float datapointX, final float datapointY)
{
if (displayTooltipCallback != null)
{
final Date datapointDate = new Date(minTimestampFinal + (Math.round((double)datapointX) * DateConstants.MILLISECONDS_PER_MINUTE));
// The graphing library doesn't give us the data point index that was clicked, so we have to look through all of the data to find it
final LineChartDataset<Date, Double> dataset = lineDatasets.get(datasetIndex);
for (int i = 0; i < dataset.getXValues().size(); ++i)
{
// Due to floating point error, we have to approximate the X into a date value
if (Math.abs(dataset.getXValues().get(i).getTime() - datapointDate.getTime()) < (DateConstants.MILLISECONDS_PER_MINUTE * 5)
&& dataset.getYValues().get(i).floatValue() == datapointY)
{
return displayTooltipCallback.onDisplayTooltipText(datasetIndex, i, Float.toString(datapointY));
}
}
}
return null;
}
We have chartTouchListeners for every chart in it we can override onSingelTapUp(MotionEvent e)
override fun onSingleTapUp(e: MotionEvent?): Boolean {
if (e != null) {
val highlight = mChart?.getHighlightByTouchPoint(e.x, e.y)
if (highlight != null) {
val x = highlight.x.toInt()
val entry = chart.data.dataSet.getEntryForIndex(x)
}
}
return super.onSingleTapUp(e)
}
Here we can get Index and entry by using highlight
One way to accomplish this is to add the index to the Entry
in the data
when first creating it:
data.addEntry(new Entry(x, y, dataSet.getEntryCount() + 1), GRAPH_DATA);
And then you can retrieve it from the Entry
after it's tapped:
public void refreshContent(Entry e, Highlight highlight) {
textView.setText("Index: " + (int) e.getData()));
...