Search code examples
c#wpfdata-bindingscottplot

Using ScottPlot in WPF


I'm quite new with WPF and data binding. I am creating a bar chart using ScottPlot in WPF User Control. After studying the ScottPlot website I am still unable to bind my chart to the code behind. I imported the ScottPlot chart into my UC and named it chartWPF. Now I have some code behind customizing the chart data. How can I connect these two together?

This is what i have as the code behind:

public UReport()
    {
        InitializeComponent();

        var plt = new ScottPlot.Plot(600, 400);
                    
        double[] values = { 26, 20, 23, 7, 16 };
        double[] positions = { 0, 1, 2, 3, 4 };
        string[] labels = { "PHP", "JS", "C++", "GO", "VB" };
        plt.AddBar(values, positions);
        plt.XTicks(positions, labels);
        plt.SetAxisLimits(yMin: 0);
        plt.SaveFig("bar_labels.png");

     
    }

and this is in my UC XAML:

<ScottPlot:WpfPlot x:Name="chartWpf"/>

Solution

  • Your code doesn't add a bar chart to the WpfPlot, it creates an uninteractive plot and adds the bar chart to that. You can access the plot object of the WpfPlot with chartWpf.Plot, so your code becomes something like this:

    public UReport() { 
        InitializeComponent();                    
        double[] values = { 26, 20, 23, 7, 16 };
        double[] positions = { 0, 1, 2, 3, 4 };
        string[] labels = { "PHP", "JS", "C++", "GO", "VB" };
    
        chartWpf.Plot.AddBar(values, positions);
        chartWpf.Plot.XTicks(positions, labels);
        chartWpf.Plot.SetAxisLimits(yMin: 0);
        chartWpf.Plot.SaveFig("bar_labels.png");     
    }