Search code examples
wpfchartslinetoolkit

How can I draw continuous line chart with wpf toolkit.


How can I draw continuous line chart with wpf toolkit. for example heart rate chart.But I can use both android and windows 8 this chart.


Solution

  • There are some 3rd party libraries on the internet. If you google it you'll find a lot. Unfortunately (as far as i know) wpf is not supported on Android platform. So for android, I cannot help.

    But, if you want to do it in the "hard way" here is a starting point: Wpf is very good at graphics. Even with the low resource (cpu,gpu,memory) devices, its performance is very good. In one of my projects I needed a continious line chart. In my scenario I have a stream of data points of 2. First one is BPM and second one is IBI. I wanted to show BPM as area graph and on top IBI as line. Here is an image:

    Chart Graph

    I made this as a user control. It contains a Canvas for chart, Textblocks for information. The controls are laid on a grid. For layout i'll not provide information while the topic is creating a chart.

    The canvas will represent chart. Green, yellow, and red vertical lines are BPM values and blue (aqua) line is IBI value. Thus I have two series. Canvas width is my window for data points. Once the window is full then it starts to scroll continiously. To achive this each serie has a queue.

    Queue<int> beatsColl, ibisColl;
    

    If each line's stroke width is 2 pixels then Queue length queueSize is canvas.width / 2. Queue is a collection works with FIFO principle. Thus this gives us a walking view of lines.

    When a new data is arrived we need to calculate the length of line. Which is: current value / Maximum value in the Queue. Then reverse it because we want to draw the line from bottom to up.

    double lineLength = 1 - ( currentValue / maxValue );
    double y1 = canvas.ActualHeight;
    double y2 = y1 * lineLength; //to calculate coordinates.
    

    The X1 and X2 coords are calculated in steps of: canvas.ActualWidth / line stroke width Then we can create line:

    //... for each points in Queue
    // i is the nTH value of Queue 
    double xX = canvas.ActualWidth - ( i * lineWidth ); 
    Line l = new Line() {
        Stroke = selectiveBrush,
        StrokeThickness = lineWidth,
        X1 = xX,
        X2 = xX,
        Y1 = y1,
        Y2 = y2
    };
    //then add the line to the canvas
    canvas.Children.Add(l);
    

    Don't forget to clear the canvas before adding new Queue points and try to update Queues like this:

    void putB( int b ) {
        beatsColl.Enqueue( b );
        if (beatsColl.Count > queueSize)
            beatsColl.Dequeue();
    }
    

    queueSize is a seperate int calculated as described above.