Created
January 30, 2013 08:06
-
-
Save mikeminutillo/4671548 to your computer and use it in GitHub Desktop.
A LinqPad extension for generating simple sparklines in output. Based on http://weblogs.asp.net/britchie/archive/2011/08/30/adding-sparklines-to-your-mvc-site-using-the-net-chart-api.aspx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Query Kind="Program"> | |
<Reference><RuntimeDirectory>\System.Web.DataVisualization.dll</Reference> | |
<Reference><RuntimeDirectory>\System.Web.dll</Reference> | |
<Namespace>System.Web.UI.DataVisualization.Charting</Namespace> | |
<Namespace>System.Drawing</Namespace> | |
</Query> | |
void Main() | |
{ | |
var r = new Random(); | |
Enumerable.Range(1, 25).Select(x => r.Next(1, 50)).AsSparkLines().Dump(); | |
} | |
public static class MyExtensions | |
{ | |
public static Image AsSparkLines(this IEnumerable<int> values, int width = 120, int height = 50, int low = 0, int high = 100) | |
{ | |
return values.Select(x => (double)x).AsSparkLines(width, height); | |
} | |
public static Image AsSparkLines(this IEnumerable<double> values, int width = 120, int height = 50, int low = 0, int high = 100) | |
{ | |
var chart = new Chart(); | |
var series = new Series(); | |
chart.Series.Add(series); | |
series.ChartType = SeriesChartType.Spline; | |
series.BorderWidth = 2; | |
var x = 0; | |
foreach(var value in values) | |
{ | |
series.Points.AddXY(DateTime.Now.AddDays(x++), value + 5); | |
} | |
var chartArea = new ChartArea(); | |
chart.ChartAreas.Add(chartArea); | |
chartArea.AxisX.LabelStyle.Enabled = false; | |
chartArea.AxisY.LabelStyle.Enabled = false; | |
chartArea.AxisX.MajorGrid.Enabled = false; | |
chartArea.AxisY.MajorGrid.Enabled = false; | |
chartArea.AxisX.MajorTickMark.Enabled = false; | |
chartArea.AxisY.MajorTickMark.Enabled = false; | |
chartArea.AxisX.LineWidth = 0; | |
chartArea.AxisY.LineWidth = 0; | |
chartArea.AxisY.Minimum = low; | |
chartArea.AxisY.Maximum = high + 10; | |
chart.Width = width; | |
chart.Height = height; | |
using(var s = new MemoryStream()) | |
{ | |
chart.SaveImage(s, ChartImageFormat.Png); | |
s.Position = 0; | |
return Image.FromStream(s); | |
} | |
} | |
} | |
// You can also define non-static classes, enums, etc. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment