Time series plot using MPAndroidChart

Viewed 257

I want to plot time series data in Android. I have a temperature sensor which reports data at every 10 seconds. I am taking that data from cloud using API. In data, I have a temperature value and its timestamp. I want to display data for 1 month and user can zoom chart till timestamp (till seconds or mins).

I tried to plot using MPAndroidChart. I have taken timestamps on X-axis and value on Y-axis. MPAndroidChart only allows float values and I have timestamps which are of long type. So I have taken first starting timestamp as 0 and calculated others by subtracting this base timestamp from it. I have done this after reading this issue. https://github.com/PhilJay/MPAndroidChart/issues/2891

I have used code from answer of this question. Here is my code snippet.

private void showChart(ArrayList<TempData> tempData, long baseTimestamp) {

    // Prepare Bar Entries
    ArrayList<BarEntry> barEntries = new ArrayList<>();

    for (int i = 0; i < tempData.size(); i++) {

        long timestamp = tempData.getTimestamp(); // Here timestamp & baseTimestamp both are in seconds.
        timestamp = timestamp - baseTimestamp;
        Log.d(TAG, "Adding entry with timestamp : " + timestamp);
        BarEntry barEntry = new BarEntry(timestamp, tempData.get(i).getValue());
        barEntries.add(barEntry);
    }

    // Initialise xAxis
    XAxis xAxis = barChart.getXAxis();
    xAxis.enableGridDashedLine(10f, 10f, 0f);
    xAxis.setTextColor(Color.BLACK);
    xAxis.setTextSize(14);
    xAxis.setDrawAxisLine(true);
    xAxis.setAxisLineColor(Color.BLACK);
    xAxis.setDrawGridLines(true);
    xAxis.setGranularity(1f);
    xAxis.setGranularityEnabled(true);
    xAxis.setAxisMinimum(0 + 0.5f); //to center the bars inside the vertical grid lines we need + 0.5 step
    xAxis.setAxisMaximum(barEntries.size() + 0.5f); //to center the bars inside the vertical grid lines we need + 0.5 step
    // xAxis.setLabelCount(xAxisLabel.size(), true); //draw x labels for 13 vertical grid lines
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setXOffset(0f); //labels x offset in dps
    xAxis.setYOffset(0f); //labels y offset in dps
    xAxis.setCenterAxisLabels(true);
    xAxis.setValueFormatter(new TimestampXAxisFormatter(baseTimestamp));
    // xAxis.setLabelCount(4);

    // Initialize Y-Right-Axis
    YAxis rightAxis = barChart.getAxisRight();
    rightAxis.setTextColor(Color.BLACK);
    rightAxis.setTextSize(14);
    rightAxis.setDrawAxisLine(true);
    rightAxis.setAxisLineColor(Color.BLACK);
    rightAxis.setDrawGridLines(true);
    rightAxis.setGranularity(1f);
    rightAxis.setGranularityEnabled(true);
    rightAxis.setAxisMinimum(0);
    rightAxis.setAxisMaximum(1000f);
    rightAxis.setLabelCount(4, true); //draw y labels (Y-Values) for 4 horizontal grid lines starting from 0 to 1000f
    rightAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);

    //initialize Y-Left-Axis
    YAxis leftAxis = barChart.getAxisLeft();
    leftAxis.setAxisMinimum(0);
    leftAxis.setDrawAxisLine(true);
    leftAxis.setLabelCount(0, true);
    leftAxis.setValueFormatter(new ValueFormatter() {
        @Override
        public String getFormattedValue(float value) {
            return "";
        }
    });

    // set the BarDataSet
    BarDataSet barDataSet = new BarDataSet(barEntries, "Time Series");
    barDataSet.setColor(Color.RED);
    barDataSet.setFormSize(15f);
    barDataSet.setDrawValues(false);
    barDataSet.setValueTextSize(12f);

    // set the BarData to chart
    BarData data = new BarData(barDataSet);
    barChart.setData(data);
    barChart.setScaleEnabled(false);
    barChart.getLegend().setEnabled(false);
    barChart.setDrawBarShadow(false);
    barChart.getDescription().setEnabled(false);
    barChart.setPinchZoom(false);
    barChart.setDrawGridBackground(true);
    barChart.invalidate();
}

class TimestampXAxisFormatter extends IndexAxisValueFormatter {

    long baseTimestamp;

    TimestampXAxisFormatter(long baseTime) {
        baseTimestamp = baseTime;
    }

    @Override
    public String getFormattedValue(float value) {

        // Add base timestamp
        long timestamp = (long) value;
        timestamp = timestamp + baseTimestamp;

        Log.d(TAG, "getFormattedValue, value : " + value);
        Log.e(TAG, "getFormattedValue, Timestamp : " + timestamp);

        // Convert from seconds back to milliseconds to format time  to show to the user
        String dateTimeInStr = new SimpleDateFormat("HH:mm:ss").format(new Date(timestamp * 1000));
        return dateTimeInStr;
    }
}

I was expecting timestamp (timestamp difference which was used to add BarEntry) in "getFormattedValue" method of TimestampXAxisFormatter. But I am getting 0.0, 2.0, 4.0, 6.0 etc. What is the mistake here because of that I am not able to receive timestamp in "getFormattedValue" method?

Anyone please help me to find out the issue and plot 1 month of data and user will be able to zoom till seconds.

Thanks in advance.

1 Answers

The value you want to show in x-axis,first add in Array list as below

final ArrayList<String> xAxisLabel = new ArrayList<>();
    xAxisLabel.add("J"); //this label will be mapped to the 1st index of the valuesList
    xAxisLabel.add("F");
    xAxisLabel.add("M");
    xAxisLabel.add("A");
    xAxisLabel.add("M");
    xAxisLabel.add("J");
    xAxisLabel.add("J");
    xAxisLabel.add("A");
    xAxisLabel.add("S");
    xAxisLabel.add("O");
    xAxisLabel.add("N");
    xAxisLabel.add("D");
    xAxisLabel.add(""); //empty label for the last vertical grid line on Y-Right Axis

Here I had made a Year Graph. Then when we are initializing the X -axis, There we can set value by using .setValueFormatter() function as shown below :-

XAxis xAxis = mBarChart.getXAxis();
xAxis.setValueFormatter(new ValueFormatter() {
        @Override
        public String getFormattedValue(float value) {
            return xAxisLabel.get((int) value);
        }

In your case, the value which you try to convert into timestamp in getFormattedValue()

public String getFormattedValue(float value) {

        // Add base timestamp
        long timestamp = (long) value;

is 1.0,2.0. etc, Thats the reason you are not geting the value as you want.

Now as You want to show data in every 10 sec, Here is the way - For Showing the data in every 10 secs, we need to add xLabel accordingly :-

ArrayList<Long> xAxisLabel = new ArrayList<>();

    //1h = 3600 seconds
    //1d = 86400 seconds
    //1w = 604800 seconds
    int seconds = 3600;
    //the loop here is incremented by 10 seconds (i+=10)
    for(int i = 0; i < seconds; i+=10){
        String time = DateFormat.format("dd-MM-yyyy HH:mm:ss", cal).toString();
        long timeStamp = cal.getTimeInMillis();
        valuesList.add((double)i);
        xAxisLabel.add(timeStamp);
        cal.add(Calendar.SECOND, 10);
    }

and then setting it in XAxis using below code :-

XAxis xAxis = mBarChart.getXAxis();
xAxis.setValueFormatter(new ValueFormatter() {
        @Override
        public String getFormattedValue(float value) {
            if (value >= 0)
            {
                int xIndex = (int)value;
                if (value > xAxisLabel.size()-1 && value <= xAxisLabel.size())
                    return "";
                if (xIndex < xAxisLabel.size())
                {
                    Long timeStamp = xAxisLabel.get(xIndex);
                    //here convert the timestamp to the appropriate String value
                    Calendar cal = Calendar.getInstance();
                    cal.setTimeInMillis(timeStamp);
                    String time = DateFormat.format("dd-MM-yyyy HH:mm:ss", cal).toString();
                    return String.valueOf(time);
                }
                return "";
            }
            return "";
        }
    });
Related