问题
I implemented line chart (MPAndroidChart library) for temperature report in my project.In X axis datetime should be plotted and Y axis temperature should be plotted.
I just added datetime as string in X axis label but it's collapsed. So please anyone guide me.
回答1:
Try the following.
To set the X Axis
XAxis xAxis = mChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setValueFormatter(new MyXAxisValueFormatter());
xAxis.setLabelsToSkip(0);
Create a new class MyXAxisValueFormatter
implement XAxisValueFormatter
public class MyXAxisValueFormatter implements XAxisValueFormatter {
@Override
public String getXValue(String dateInMillisecons, int index, ViewPortHandler viewPortHandler) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM");
return sdf.format(new Date(Long.parseLong(dateInMillisecons)));
} catch (Exception e) {
return dateInMillisecons;
}
}
Hope this helps
回答2:
Using version 3.0+ of the MPAndroidChart:
Set formatter to the x axis (created below):
// Formatter to adjust epoch time to readable date
lineChart.xAxis.setValueFormatter(new LineChartXAxisValueFormatter());
Create a new class LineChartXAxisValueFormatter:
public class LineChartXAxisValueFormatter extends IndexAxisValueFormatter {
@Override
public String getFormattedValue(float value) {
// Convert float value to date string
// Convert from seconds back to milliseconds to format time to show to the user
long emissionsMilliSince1970Time = ((long) value) * 1000;
// Show time in local version
Date timeMilliseconds = new Date(emissionsMilliSince1970Time);
DateFormat dateTimeFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
return dateTimeFormat.format(timeMilliseconds);
}
}
When the entries are added to the chartDataArray
they are added in seconds, not milliseconds, to avoid potential precision issues with inputting as a float (i.e. milliseconds divided by 1000).
chartDataArray.add(new Entry(secondsSince1970Float, yValueFloat));
Happy coding!
回答3:
If it still actually...
class DateAxisValueFormatter implements IAxisValueFormatter {
private String[] mValues;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.hh");
public DateAxisValueFormatter(String[] values) {
this.mValues = values; }
@Override
public String getFormattedValue(float value, AxisBase axis) {
// "value" represents the position of the label on the axis (x or y)
return mValues[(int) value];
}
}
And your must on Create put
String[]
values(public DateAxisValueFormatter(String[] values) )
where each value is a DateString. Data series Entries for X (new Entry(forX,forY)) must be aflat array = 0,1,2,3,4
Sorry, my poor English, I am from Russia. From 1988 main chief of RealTime Control System Developer Company for Hydro Power Plants (www.asu-epro.ru). Borodatov Michael miclosoft@mail.ru
来源:https://stackoverflow.com/questions/41426021/how-to-add-x-axis-as-datetime-label-in-mpandroidchart