Search code examples
androidchartsandroidplotandroid-graphview

AndroidPlot: How i can change the domain data?


I use actually the AndroidPlot library to use a simple chart in my android project but I don't know how i can change the values of domain zone.

More specific, this line:

mySimpleXYPlot.setDomainValueFormat(new DecimalFormat("#"));

In the web site said that i can use another formats and its true, but if I use for example:

SimpleDateFormat("dd-MM-yyyy")

In the chart appears "31-12-1969" in all domain values.

Somebody know how I can change that date? or use another format (like String)?


Solution

  • Late answer, but maybe will be useful to other people.

    I also had a hard time with this issue, especially since I am Java beginner. I implemented a custom formatter. Seems a bit ugly solution but it works. Idea is the following:

    • take only Y axis for values, and leave X axis as indexes into an array (as Androidplot tutorial suggests, use using ArrayFormat.Y_VALS_ONLY, // Y_VALS_ONLY means use the element index as the x value)
    • each time your data changes, you need to pass to the Plot a new formatter with your new data for X axis

    Here are some code snippets.

    First is the class which transforms array index to a custom label String:

    public class MyIndexFormat extends Format {
    
        public String[] Labels = null;
    
            @Override
            public StringBuffer format(Object obj, 
                    StringBuffer toAppendTo, 
                    FieldPosition pos) {
    
                // try turning value to index because it comes from indexes
                // but if is too far from index, ignore it - it is a tick between indexes
                float fl = ((Number)obj).floatValue();
                int index = Math.round(fl);
                if(Labels == null || Labels.length <= index ||
                        Math.abs(fl - index) > 0.1)
                    return new StringBuffer("");    
    
                return new StringBuffer(Labels[index]); 
            }
    

    And here is how I attach it to the Plot:

    MyIndexFormat mif = new MyIndexFormat ();
    mif.Labels = // TODO: fill the array with your custom labels
    
    // attach index->string formatter to the plot instance
    pricesPlot.getGraphWidget().setDomainValueFormat(mif); 
    

    This trick works also for dynamic updates.

    NOTICE: Androidplot seems to have problems with drawing horizontal lines, so if your data has the same Y values, you might get strange results, I already asked for help on this issue.