使用MPAndroidChart自定义XAxis标签

时间:2018-01-09 14:37:32

标签: android real-time mpandroidchart linechart

我是MPAndroidChart的新手,我想在LineChart的XAxis上实时显示时间。我想只显示传入数据的最后10秒,如下图所示。我的采样频率为25Hz,因此我需要显示250个值才能有10秒的记录。

Something like this

但是,我真的不知道该怎么做。我想我必须使用IAxisValueFormatter

目前,我的传入值会添加到数据集中,如下所示:

addEntry(myDataSet, new Entry(myDataSet.getEntryCount(), myNewValue));

但也许我需要这样做:

/* add 40 ms on xAxis for each new value */
addEntry(myDataSet, new Entry(myLastTimeStamp + 40, myNewValue));

然后创建一个格式化程序,将X值转换为字符串,如" xxx秒"并仅显示" 0s"," 5s"和" 10s"。

我不知道它是否有效但是有更好的方法吗?

THX

1 个答案:

答案 0 :(得分:6)

所以我在这里看到两个问题 1.您需要在10秒内绘制250个值 2.正确格式化X轴 因此,对于第一个问题的解决方案,您必须在十秒内显示250个值。所以你的x轴实际上将有250个数据点,因为你正在做:

addEntry(myDataSet, new Entry(myDataSet.getEntryCount(), myNewValue));

所以在1秒内你将得到25分。

现在有了所有这些数据,我们就可以使用XAxis。

xAxis = chart.getXAxis();
xAxis.setAxisMinimum(0);
xAxis.setAxisMaximum(250); // because there are 250 data points
xAxis.setLabelCount(3); // if you want to display 0, 5 and 10s which are 3 values then put 3 else whatever of your choice.
xAxis.setValueFormatter(new MyFormatter());

然后你的格式化工具必须看起来像这样:

public class MyFormatter implements IAxisValueFormatter {
@Override
public String getFormattedValue(float value, AxisBase axis) {
//Modify this as per your needs. If you need 3 values like 0s, 5s and 10s then do this.
//0 mod 125 = 0 Corresponds to 0th second
//125 mod 125 = 0 Corresponds to 5th second
//250 mod 125 = 0 Corresponds to 10th second
    if(value % 125 == 0){
       int second = (int) value / 25; // get second from value
       return second + "s" //make it a string and return
    }else{
       return ""; // return empty for other values where you don't want to print anything on the X Axis
    }
}

希望这能清除一切。干杯!