How to show Time on DateTime axis (Primary axis) of Line chart after loading data from API response using SFChart in Xamarin forms?

Time on DateTime axis (Primary axis) of Line chart showing incorrect time after loading data from API response using SFChart in Xamarin forms.


I am using SFChart - Line chart to show graph having time on x-axis and values on y-axis.

I want to show 24 hours data on graph.

I am getting date time and values from API response.

Before loading data I can see correct time on X-Axis as shown in below image

IMG_0255.PNG


I have set IntervalType as Hour and Intervals as 1 for DateTime-Axis (Primary axis).

but after loading data, time on x-axis is repeating 12AM, 4PM and 8AM as shown in below image.

IMG_0256.PNG

I am sharing code so that you will get clear idea what I have done and is there anything wrong in code.

Xaml

<Frame HasShadow="False"

                   x:Name="outframe"

                   CornerRadius="{OnIdiom Phone=15,Tablet=25}"

                   Padding="0"

                   OutlineColor="#ffffff"

                   BackgroundColor="#4A4541"

                   WidthRequest="{OnIdiom Phone=320,Tablet=600}"

                   HeightRequest="{OnIdiom Phone=450,Tablet=475}"

                   VerticalOptions="Center"

                   HorizontalOptions="Center"

                   IsClippedToBounds="True">

                <StackLayout VerticalOptions="FillAndExpand"

                             HorizontalOptions="FillAndExpand" BackgroundColor="#4A4541">

                    <Label Text="GRAPH"

                           FontFamily="{StaticResource PrimaryFontBold}"

                           TextColor="White"

                           VerticalTextAlignment="Center"

                           Margin="0,50,0,0"

                           HorizontalTextAlignment="Center"

                           FontSize="{OnIdiom Phone=16,Tablet=22}"

                           HorizontalOptions="Center" />

                    <sfcharts:SfChart HeightRequest="200"

                                      WidthRequest="300"

                                      HorizontalOptions="CenterAndExpand"

                                      VerticalOptions="CenterAndExpand"

                                      BackgroundColor="#4A4541"

                                      AreaBorderColor="White" AreaBackgroundColor="#4A4541">

                        <sfcharts:SfChart.PrimaryAxis>

                            <sfcharts:DateTimeAxis IntervalType="Hours" Interval="1" LabelRotationAngle="90" >

                                <sfcharts:DateTimeAxis.LabelStyle>

                                    <sfcharts:ChartAxisLabelStyle LabelFormat = "hh:mm tt" TextColor="#FDDFBD">

                                </sfcharts:ChartAxisLabelStyle>

                            </sfcharts:DateTimeAxis.LabelStyle>

                        </sfcharts:DateTimeAxis>

                        </sfcharts:SfChart.PrimaryAxis>

                        <sfcharts:SfChart.SecondaryAxis>

                            <sfcharts:NumericalAxis Minimum="0"

                                                     Maximum="60"

                                                     Interval="10" >

                            <sfcharts:NumericalAxis.LabelStyle>

                                    <sfcharts:ChartAxisLabelStyle TextColor="White">

                                </sfcharts:ChartAxisLabelStyle>

                            </sfcharts:NumericalAxis.LabelStyle>

                                <sfcharts:NumericalAxis.MajorGridLineStyle>

                                    <sfcharts:ChartLineStyle StrokeColor="#bae1f2"/>

                                </sfcharts:NumericalAxis.MajorGridLineStyle>

                                </sfcharts:NumericalAxis>

                        </sfcharts:SfChart.SecondaryAxis>

                        <sfcharts:StackingLineSeries x:Name="MyLineChart"

                                                     XBindingPath="Key"

                                                     YBindingPath="Value" ItemsSource="{Binding LineData}"

                                                     ListenPropertyChange="True" StrokeWidth="1" Color="#FDDFBD" >

                            <sfcharts:StackingLineSeries.DataMarker>

                                <sfcharts:ChartDataMarker MarkerWidth="2" MarkerHeight="2" ShowLabel="False" ShowMarker="true" MarkerBorderColor="#bae1f2" MarkerBorderWidth="2" MarkerColor="White"/>

                            </sfcharts:StackingLineSeries.DataMarker>

                        </sfcharts:StackingLineSeries>

                    </sfcharts:SfChart>

                </StackLayout>

            </Frame>


Codebehind.cs


    RViewModel rViewModel;

     public RRGraph()

        {

            InitializeComponent();

            rViewModel = new RViewModel();

            BindingContext = rViewModel;

        }


Model.cs


    public class ChartData

    {

        public string name { get; set; }

        public ObservableCollection<LineChartData> DataPoints { get; set; }

    }


    public class LineChartData:INotifyPropertyChanged

    {

        public LineChartData(string key, double value)

        {

            Value = value;

            Key = key;

        }

        private double value;

        public double Value

        {

            get { return value; }

            set

            {

                this.value = value;

                RaisePropertyChanged("Value");

            }

        }


        private string key;

        public string Key

        {

            get { return key; }

            set

            {

                DateTime dt = DateTime.Parse(value);


                value = dt.ToString("hh:mm tt");

                key = value;

                RaisePropertyChanged("Key");

            }

        }


        public event PropertyChangedEventHandler PropertyChanged;

        void RaisePropertyChanged(string name)

        {

            if (PropertyChanged != null)

                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

        }

    }


ViewModel.cs


    public class RViewModel:INotifyPropertyChanged

    {

        public ChartData ChartData { get; set; }

        public ObservableCollection<LineChartData> LineData

        {

            get { return lineData; }

            set

            {

                lineData = value;

                RaisePropertyChanged(nameof(LineData));

            }

        }


        public event PropertyChangedEventHandler PropertyChanged;

        void RaisePropertyChanged(string name)

        {

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

        }


        public RespiratoryViewModel(string roomId)

        {

            LoadData();

        }


        public async void LoadData()

        {

            try

            {

//API call

                ChartData = await AppClass.DataManager.GetRR();

                LineData = ChartData.DataPoints;

            }

            catch (Exception ex)

            {

                Crashes.TrackError(ex);

            }

        }

    }



10 Replies

DD Devakumar Dhanapoosanam Syncfusion Team June 8, 2022 09:53 AM UTC

Hi Bhakti B,


We would like to let you know DateTimeAxis default range is 24hours, hence it shows 24 hours data on graph at initial without loading any data. After adding data nice axis range calculated based on the provided data.


We can show fixed range in graph by using the axis AutoScollingDelta as per in the below code example.


<chart:SfChart.PrimaryAxis>

    <chart:DateTimeAxis IntervalType="Hours" Interval="1" LabelRotationAngle="90"

                        AutoScrollingDelta="24" AutoScrollingDeltaType="Hours"

                        AutoScrollingMode="Start" EnableAutoIntervalOnZooming="False">

        <chart:DateTimeAxis.LabelStyle>

            <chart:ChartAxisLabelStyle LabelFormat = "hh:mm tt"/>

        </chart:DateTimeAxis.LabelStyle>

    </chart:DateTimeAxis>

</chart:SfChart.PrimaryAxis>


Output:
Chart, line chart

Description automatically generated


https://help.syncfusion.com/xamarin/charts/axis#autoscrollingdelta

https://www.syncfusion.com/kb/7721/how-to-display-fixed-number-of-data-points-in-chart

https://www.syncfusion.com/kb/8621/how-to-show-the-fixed-number-of-data-points


Please find the sample from the attachment below and let us know if you need any further assistance on this.


Regards,

Devakumar D


Attachment: SF_175505_ce1a536.zip


BB Bhakti B June 8, 2022 11:14 AM UTC

Hi Devakumar Dhanapoosanam,

I tried above code shared by you. Unfortunately it won’t work for me.

I tried and I have got answer for my question. Issue is with DataType used for Key.

I am getting date time in string format and values in double from API response.

I had kept that Key as string only instead of that it’s datatype should be DateTime.

So I have added one parameter DateValue of datatype DateTime in LineChartData Model.

public DateTime DateValue { get; set; }

public LineChartData(string key, double value)

{

Value = value;

Key = key;

DateValue = DateTime.ParseExact(Key, "hh:mm tt", new CultureInfo("en-US"));

}


And in xaml set that DateValue to XBindingPath

XBindingPath="DateValue"

YBindingPath="Value" ItemsSource="{Binding LineData}"

ListenPropertyChange="True" StrokeWidth="1" Color="#FDDFBD" >


I got my mistake while referencing below link.

https://www.syncfusion.com/forums/147859/how-to-set-datetime-axis-for-12-am-to-11-59-pm-and-scroll-is-not-working



DD Devakumar Dhanapoosanam Syncfusion Team June 9, 2022 07:28 AM UTC

Hi Bhakti B,

Thanks for your update. We are glad to know that you have found solution.


Please let us know if you need any further assistance.


Regards,

Devakumar D



BB Bhakti B June 13, 2022 03:01 PM UTC

Hi Devakumar Dhanapoosanam,

I am facing issue to plot points for graph when I am working with Localisation.

I want to convert it into Spanish.


There is an exception String was not recognized as a valid DateTime for DateTime conversion.

I am getting Date and Time like 6/13/2022 12:10:15 PM in string format.

I want to convert this string into DateTime format with es-ES culture.

In my above code I am passing that converted Time to DateValue parameter. DateValue is XBindingPath.

Which method should I use to convert this dateTime with es-ES culture.


How to convert string “M/dd/yyyy hh:mm:ss tt” to "hh:mm tt" DateTime format from English to Spanish in Xamarin forms? 



DD Devakumar Dhanapoosanam Syncfusion Team June 15, 2022 03:07 AM UTC

Hi Bhakti B,


Please refer the below link for converting datetime string into datetime value.
https://stackoverflow.com/questions/5938694/datetime-parse-american-date-format-c-sharp


We can apply the datetime format Spanish es-ES culture using axis LabelCreated event as per in the below code example.


<chart:DateTimeAxis IntervalType="Hours" Interval="1"

                    LabelCreated="DateTimeAxis_LabelCreated">

</chart:DateTimeAxis>


private void DateTimeAxis_LabelCreated(object sender, ChartAxisLabelEventArgs e)

{

    DateTime date = DateTime.FromOADate(e.Position);

    e.LabelContent = date.ToString("hh:mm tt", new CultureInfo("es-ES"));

}


Please refer the below link for more details

https://www.syncfusion.com/kb/11289/how-to-customize-the-axis-label-format-based-on-the-culture-in-xamarin-forms-chart-sfchart

https://help.syncfusion.com/xamarin/charts/axis#event

https://help.syncfusion.com/xamarin/charts/localization


Please let us know if you need any further assistance.


Regards,

Devakumar D



BB Bhakti B June 16, 2022 09:11 AM UTC

Hi Devakumar Dhanapoosanam,

Thank you for your help. It's working as expected now.




BB Bhakti B June 16, 2022 12:18 PM UTC

Hi Devakumar Dhanapoosanam,

I am getting data for previous dates as well. but I need to show today’s data only. I am getting UTC date time in string format which needs to convert in local time zone.

I bind MaximumDate and MinimumDate but I can’t see any point plotted on graph.

Please check below code and let me know am I wrong somewhere?


XAML


ViewModel.cs


public DateTime MinimumDate { get; set; }

public DateTime MaximumDate { get; set; }

public ViewModel()

{

MinimumDate = DateTime.Today;

MaximumDate = DateTime.Now;

}



DD Devakumar Dhanapoosanam Syncfusion Team June 17, 2022 12:35 PM UTC

Hi Bhakti B,


We have checked binding Minimum and Maximum properties of DateTimeAxis and it was working proper at our end with the provided custom range. Also, we would like to suggest implementing notify property changes for the Minimum and Maximum property in viewmodel as per in below code example.


ViewModel.cs


private
DateTime maximumDate;

 

public DateTime MaximumDate

{

    get { return maximumDate; }

    set

    {

        maximumDate = value;

        OnPropertyChanged(nameof(MaximumDate));

    }

}

 

private DateTime minimumDate;

 

public DateTime MinimumDate

{

    get { return minimumDate; }

    set

    {

        minimumDate = value;

        OnPropertyChanged(nameof(MinimumDate));

    }

}


<chart:DateTimeAxis IntervalType="Hours" Interval="1" LabelRotationAngle="90"

                    AutoScrollingDelta="24" AutoScrollingDeltaType="Hours"

                    AutoScrollingMode="Start" EnableAutoIntervalOnZooming="False"

                    Minimum="{Binding MinimumDate}"

                    Maximum="{Binding MaximumDate}">

</chart:DateTimeAxis>


Could you please check whether your data points added were in the provided Minimum and Maximum range values?

If you are still facing the problem, please share more details or share the issue reproducing sample by modifying the attached sample which will help us to replicate the issue and to provide the solution at earliest.


Regards,

Devakumar D


Attachment: SF_175505_38f396b8.zip


BB Bhakti B June 21, 2022 05:22 PM UTC

Hi Devakumar Dhanapoosanam,

Thank you for your help. It's working as expected.



DD Devakumar Dhanapoosanam Syncfusion Team June 22, 2022 04:54 AM UTC

Hi Bhakti B,


Thanks for your update.


Please let us know if you need any further assistance.


Regards,

Devakumar D


Loader.
Up arrow icon