Friday, August 03, 2007

Sparklines for WinForms

I wanted a Windows Forms implementation of Edward Tufte's "Sparklines". I couldn't find one, so wrote my own.

It's just very basic at present. You provide it a collection of numbers, representing the data points to be graphed in a sparkline. You also tell it how many horizontal pixels to allocate to each data point, and how the total height of the sparkline in pixels. Then it renders the sparkline for you.

You can use the code as a WinForms Control (SparklineControl) or you can programatically render to any Graphics object you like, using SparklineReneder.

Here's the source code, and here is an example of using it. Please leave any questions as comments on this post.

Example:


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

spark.Height = 20;
spark.Renderer.PixelsPerElement = 5;
panel1.Controls.Add(spark);
}

SparklineControl spark = new SparklineControl();

private void button1_Click(object sender, EventArgs e)
{
List<int?> values = new List<int?>();
foreach(string s in textBox1.Lines)
{
string trimmed = s.Trim();
if(string.IsNullOrEmpty(trimmed))
values.Add(null);
else 
values.Add(int.Parse(trimmed));
}

spark.Renderer.DataElements = values;
spark.Invalidate();
}

0 Comments:

Links to this post:

Create a Link

<< Home