Линейный график показывает информацию о точке постукивания - PullRequest
0 голосов
/ 29 января 2019

Я реализую небольшое приложение с Xamarin Forms для веб-страницы, дело в том, что в этом вебе есть линейная диаграмма с несколькими записями, и если пользователь нажимает на точку линии, отображается информация об этой точке, какВы можете видеть на картинке:

Линейная веб-диаграмма

После некоторой работы я мог бы создать более или менее похожую линейную диаграмму с помощью плагина OxyPlot.Xamarin.Formsс несколькими записями, которые показывают точки

Линейная диаграмма моего приложения

Это мой код:

        OnPropertyChanged("GraphModel");

        var model = new PlotModel
        {
            LegendPlacement = LegendPlacement.Outside,
            LegendPosition = LegendPosition.BottomCenter,
            LegendOrientation = LegendOrientation.Horizontal,
            LegendBorderThickness = 0
        };
        model.PlotType = PlotType.XY;
        model.InvalidatePlot(false);

        Dictionary<string, List<Prices>> values = HistoricData[Selected.ProductId];

        int colorIndex = 0;
        List<string> x_names = new List<string>();

        foreach (var item in values.Keys)
        {

            if (item.ToUpper() == Selected.ProductName) { SelectedIndex = colorIndex; }
            var lineSeries = new LineSeries()
            {
                Title = item,
                MarkerType = MarkerType.Circle,
            };
            lineSeries.MarkerResolution = 3;
            lineSeries.MarkerFill = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
            lineSeries.MarkerStroke = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
            lineSeries.MarkerSize = 3;

            var points = new List<DataPoint>();


            lineSeries.Color = OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);

            foreach (var price in values[item])
            {
                points.Add(new DataPoint(price.Week+price.Year, price.Price));

            }

            if (ButtonsVisibility.Count == 0)
            {
                lineSeries.IsVisible = (Selected.ProductName == item.ToUpper()) ? true : false;
            }
            else
            {
                lineSeries.IsVisible = ButtonsVisibility[colorIndex];
            }


            lineSeries.ItemsSource = points;
            lineSeries.MarkerType = OxyPlot.MarkerType.Circle;
            model.Series.Add(lineSeries);
            colorIndex++;
        }

        NumButtons = colorIndex;
        LinearAxis yaxis = new LinearAxis();
        yaxis.Position = AxisPosition.Left;
        yaxis.MajorGridlineStyle = LineStyle.Dot;
        model.Axes.Add(yaxis);

        LineChart = model;
        OnPropertyChanged("GraphModel");
        return LineChart;

Я сомневаюсь, какое свойство мне следуетработать и показывать хотя бы значение конкретной точки, я видел свойство OnTouchStarted, но только для всех LineSeries, а не для одной точки.В некоторых статьях я читал, что в OxyPlot.Xamarin.Forms есть трекер.Я добавил эту строку в свой код:

lineSeries.TrackerFormatString = "X={2},\nY={4}";

Предполагается, что при щелчке показываются значения x и y, но ничего не отображается, какие-либо предложения?Должно отображаться что-то вроде этого: Информация о трекере в точке

Из следующего примера: Пример трекера

Обновленный код

public PlotModel GetLineChart()
{
    OnPropertyChanged("GraphModel");

    var model = new PlotModel
    {
        LegendPlacement = LegendPlacement.Outside,
        LegendPosition = LegendPosition.BottomCenter,
        LegendOrientation = LegendOrientation.Horizontal,
        LegendBorderThickness = 0
    };
    model.PlotType = PlotType.XY;
    model.InvalidatePlot(false);

    Dictionary<string, List<Prices>> values = HistoricData[Selected.ProductId];

    int colorIndex = 0;
    List<string> x_names = new List<string>();

    foreach (var item in values.Keys)
    {

        if (item.ToUpper() == Selected.ProductName) { SelectedIndex = colorIndex; }
        var lineSeries = new LineSeries()
        {
            Title = item,
            MarkerType = MarkerType.Circle,
            CanTrackerInterpolatePoints = false

        };
        lineSeries.MarkerResolution = 3;
        lineSeries.MarkerFill = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
        lineSeries.MarkerStroke = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
        lineSeries.MarkerSize = 3;

        var points = new List<DataPoint>();


        lineSeries.Color = OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);

        foreach (var price in values[item])
        {
           points.Add(new DataPoint(price.Week+price.Year, price.Price)); 
        }

        if (ButtonsVisibility.Count == 0)
        {
            lineSeries.IsVisible = (Selected.ProductName == item.ToUpper()) ? true : false;
        }
        else
        {
            lineSeries.IsVisible = ButtonsVisibility[colorIndex];
        }


        lineSeries.ItemsSource = points;
        lineSeries.MarkerType = OxyPlot.MarkerType.Circle;

        lineSeries.TrackerFormatString = "X={2},\nY={4}";

        lineSeries.TextColor = OxyPlot.OxyColor.Parse(SubCategoriesViewModel.AvailableColors[colorIndex]);
        model.Series.Add(lineSeries);
        colorIndex++;
    }

    NumButtons = colorIndex;

    LinearAxis yaxis = new LinearAxis();
    yaxis.Position = AxisPosition.Left;
    //yaxis.StringFormat = "X={2},\nY={4}";
    yaxis.MajorGridlineStyle = LineStyle.Dot;
    model.Axes.Add(yaxis);

    LineChart = model;
    OnPropertyChanged("GraphModel");
    return LineChart;

}

}

 protected async override void OnAppearing()
        {
            await _viewModel.LinearViewModel.GetSubCategoryHistoricWeekPrices(App.ViewModel.LoginViewModel.SesionToken, FROM_DATE, TO_DATE);
            Plot.Model = _viewModel.LinearViewModel.GetLineChart();
            PlotController controller = new PlotController();
            controller.UnbindAll();
            controller.BindTouchDown(PlotCommands.PointsOnlyTrackTouch);
            Plot.Controller = controller;



            AddButtons();


        }

XAML Декларация для просмотра графика:

<oxy:PlotView 
            Grid.Row="2"
            Grid.RowSpan="2"
            Grid.ColumnSpan="4"            
            x:Name="Plot" />

1 Ответ

0 голосов
/ 29 января 2019

Ваша проблема заключается в следующей строке.

lineSeries.TrackerKey = "X={2},\nY={4}";

Когда вы используете series.TrackerKey, вы указываете, что используете CustomTracker, а в данном случае - нет.Пользовательские трекеры были бы полезны, если вам нужно использовать разные трекеры для каждой серии в модели.

В вашем случае вы должны удалить эту строку и использовать только TrackerFormatString.

lineSeries.TrackerFormatString = "X={2},\nY={4}";

Это будетпоказать всплывающую подсказку, используя параметры строки формата, где {2} означает значение X, а {4} означает Y. Для вашей информации, следующие заполнители:

{0} = Title of Series
{1} = Title of X-Axis
{2} = X Value
{3} = Title of Y-Axis
{4} = Y Value

Если вам необходимо включить дополнительную / пользовательскую информациюв вашем инструменте ваша точка данных должна включать эту информацию.Это где интерфейс IDataPointProvider становится удобным.Вы можете создать пользовательскую точку данных, реализовав интерфейс, а затем включить в свою подсказку ту же информацию.

Обновление на основе комментариев

Дополнительно включить«Touch», вы можете указать TouchDown в PlotController.Вы можете сделать это, определив PlotController в вашей viewModel следующим образом.

public PlotController CustomPlotController{get;set;}

Вы можете определить свойство следующим образом.

CustomPlotController = new PlotController();
CustomPlotController.UnbindAll();
CustomPlotController.BindTouchDown(PlotCommands.PointsOnlyTrackTouch);

И в вашем Xaml

<oxy:Plot Controller="{Binding CustomPlotController}"......
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...