Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

android - Mpandroidchart text not properly showing on x axis on line chart

I am working on Mpandroidchart. I have created a line chart and tried to place strings on my xaxis.

final ArrayList<String> xAxisLabel = new ArrayList<>(Arrays.asList("March","April","May"));



private ArrayList<Entry> lineChartDataSet(){
    ArrayList<Entry> dataSet = new ArrayList<Entry>();

    dataSet.add(new Entry(1,40));
    dataSet.add(new Entry(2,10));
    dataSet.add(new Entry(3,15));    
    return  dataSet;


}

 lineDataSet = new LineDataSet(lineChartDataSet(),"data set");
 XAxis xAxis = lineChart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setDrawGridLines(false);

    //String setter in x-Axis
    xAxis.setValueFormatter(new com.github.mikephil.charting.formatter.IndexAxisValueFormatter(xAxisLabel));
    xAxis.setGranularity(1f);
    xAxis.setGranularityEnabled(true);

Output

enter image description here

In the above image, you can see that month names are not properly placed. i.e march is not displaying and only april and may are shown.

Expected Output

enter image description here

How can I do it?

Any help would be highly appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of IndexAxisValueFormatter in MPAndroidChart version v3.1.0 you can use a custom ValueFormatter and override String getAxisLabel(float value, AxisBase axis) method where you can define your own logic to replace for each X value its corresponding String. Example based on your data Set will be like below:

xAxis.setValueFormatter(new ValueFormatter() {
  @Override
  public String getAxisLabel(float value, AxisBase axis) {
     String label = "";
     if(value == 1)
       label = "March";
     else if(value == 2)
       label = "April";
     else if(value == 3)
       label = "May";
     return label;
   }
}); 

And the result will be like below:

chart


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...