Category / Section
How to plot date-time values in vertical axes?
1 min read
To plot date-time values in y-axis, convert the date-time values to double while populating the items source for Xamarin Chart, and reverse the conversion (double to date-time) in the LabelCreated event of ChartAxis. By using the NumericalAxis with above conversions, you can display the date-time values in y-axis.
Code snippets
C#
public class ViewModel { public ObservableCollection<ChartDataPoint> Data { get; set; } public ViewModel() { Data = new ObservableCollection<ChartDataPoint>(); DateTime start = new DateTime(1970, 1, 1); //Converting date time value to its respective double value. Data.Add(new ChartDataPoint(new DateTime(2010, 1, 1), (new DateTime(2010, 1, 1, 1, 0, 0) - start).TotalMilliseconds)); Data.Add(new ChartDataPoint(new DateTime(2010, 2, 1), (new DateTime(2010, 1, 1, 2, 0, 0) - start).TotalMilliseconds)); Data.Add(new ChartDataPoint(new DateTime(2010, 3, 1), (new DateTime(2010, 1, 1, 3, 0, 0) - start).TotalMilliseconds)); Data.Add(new ChartDataPoint(new DateTime(2010, 4, 1), (new DateTime(2010, 1, 1, 4, 0, 0) - start).TotalMilliseconds)); Data.Add(new ChartDataPoint(new DateTime(2010, 5, 1), (new DateTime(2010, 1, 1, 5, 0, 0) - start).TotalMilliseconds)); } }
XAML
<chart:SfChart > <chart:SfChart.PrimaryAxis> <chart:DateTimeAxis /> </chart:SfChart.PrimaryAxis> <chart:SfChart.SecondaryAxis> <chart:NumericalAxis LabelCreated="NumericalAxis_LabelCreated"/> </chart:SfChart.SecondaryAxis> . . . </chart:SfChart>
C#
private void NumericalAxis_LabelCreated(object sender, Syncfusion.SfChart.XForms.ChartAxisLabelEventArgs e) { double value = Convert.ToDouble(e.LabelContent); //Converting corresponding double value to data time value. DateTime date = (new DateTime(1970, 1, 1).AddMilliseconds(value)); e.LabelContent = String.Format("{0:HH:mm}", date); }
Sample application
Output: