All 4 books by Edward Tufte now in paperback editions, $100 for all 4 Visual Display of Quantitative Information Envisioning Information Visual Explanations Beautiful Evidence Paper/printing = original clothbound books. Only available through ET's Graphics Press: catalog + shopping cart All 4 clothbound books, autographed by the author$150 catalog + shopping cart Edward Tufte e-books Immediate download to any computer: Visual and Statistical Thinking $2 The Cognitive Style of Powerpoint$2 Seeing Around + Feynman Diagrams $2 Data Analysis for Politics and Policy$2 catalog + shopping cart Edward Tufte one-day course, Presenting Data and Information San Francisco CA, December 4, 5, 6 San Jose CA, December 8 catalog + registration
Sparklines: computer code implementation

.

-- Robert Gower (email)

Response to Sparkline Implementation

It is possible to do the MLB or NFL sparkline thing in Excel with no VBA code, using separate adjacent cells for each game. Set the column width to .4 for each column needed. As above, the data is kept in a separate worksheet. Using the MLB example, the database would have three rows of data per team -- one for the win/loss (1/0), one for home/away/off (1,0, ), and one for shutout or not (1,0). On the worksheet which displays the results, use the VLOOKUP function to specify the "|" character or a blank for each game (each game being in successive columns of the same row for a team. Use one row for win, the next row for loss. Use the conditional formatting feature in Excel, along with the VLOOKUP function, to specify whether a cell displays a bottom cell border or a top cell border (depending on whether the game is a win or a loss. To the left of the win/loss line, we have two columns. The leftmost column contains a seed number specifying the ID for the team. The other includes a formula to retrieve the team name from a database stored on a separate worksheet. Since each team's record uses two rows, a second row under the team name, contains a formula to retrieve the league and division info for that team.

If this helps, great. If not, or more info needed, please e-mail me directly if you are interested. Fascinating concept, that we intend to use with many of our clients.

MANY BLESSINGS!

-- Michael W Cristiani (email)

Response to Sparkline Implementation

You can do amazingly small graphs in Excel by scaling your numbers carefully and popping each graph into one of the rectangles created by having grid lines on an Excel graph.

I managed to do one so small it occupies the height of an ordinary row on a spreadsheet. Visit http://www.internalcontrolsdesign.co.uk/reportdesign/

-- Matthew Leitch (email)

Response to Sparkline Implementation

This thread shows an example of the MLB sparklines in Excel with no VBA coding. Uses database lookups and cell formatting. Note that the first few Yankee games also include the score, represented by successive dots (.), one for each run scored. Here, both the outcome of the game and the score are clearly visible. This approach uses more real estate than just the won/lost whiskers, but it also presents more info.

MANY BLESSINGS!

-- Michael W Cristiani (email)

Response to Sparkline Implementation

I recently attended ET's class in Durham, and began searching on how to typeset sparklines. I ran across a thread by Bil Kleb on news:comp.text.tex, hoping I would find a solution, but didn't. So, I researched and was able to find that pstricks in LaTeX helps immensely. I just presented a report this morning using sparklines, and it went over very well (2214 numbers, 97 sparklines, 1 11×17 two-sided).

Below is a snipit of LaTeX code I used for my report this morning. It has a sparkline, norms in yellow, red dot with red number, and a three number running average summary in blue (similar to the mutual fund example, except I added timeframe subscripts). In the code below the preamble is red, and the body is blue.


% Do not pdflatex!  Run LaTeX... then dvips... then ps2pdf.

\documentclass{article}

\usepackage{pstricks}
\usepackage{color}

\newcommand{\Red}[1]{\textcolor[rgb]{1.00,0.00,0.00}{#1}}
\newcommand{\Blue}[1]{\textcolor[rgb]{0.00,0.00,1.00}{#1}}

\newcommand{\Data}[5]{\textsf{#1 \Red{#2} \Blue{#3${\sf _{3m}}$} \Blue{#4${\sf _{6m}}$} \Blue{#5${\sf _{1y}}$}}}
\newcommand{\Target}[4]{\pspolygon[fillstyle=solid,fillcolor=yellow,linecolor=yellow](#1,#3)(#1,#4)(#2,#4)(#2,#3)}


\begin{document}

% Tracks Staffing Vacancy Rate
\psset{linewidth=0.3pt, unit=.005in}
\begin{pspicture}(1,1)(55,20)
% Sets the shaded box in the background, see \Target definition above
\Target{1}{55}{0}{7}
% Draws the sparkline
\psline(1,6.67)(3,6.67)(5,6.67)(7,6.67)(9,6.67)(11,8.00)
(13,5.33)(15,2.67)(17,5.33)(19,4.00)(21,2.67)(23,2.67)
(25,6.10)(27,9.86)(29,15.13)(31,17.10)(33,20.39)(35,18.42)
(37,10.68)(39,3.70)(41,8.97)(43,16.50)(45,20.20)
(47,17.50)(49,10.40)(51,5.70)(53,10.90)
% Draws the red dot
\pscircle[fillstyle=solid,fillcolor=red,linecolor=red](53,10.90){2}
\end{pspicture}
% Gives the description, recent value, and running averages, see \Data definition above
\Data{Dept A}{10.9\%}{9.0\%}{13.5\%}{13.4\%}

...

\end{document}



The tricky part is the \psset{...} argument and getting the line to be the height of the text (try to aim for 0.1in or about 7pt), and also trying to bank to 45 degrees. There is great documentation at http://pstricks.de. I am working on creating a library of "Tufte-esque" graphics functions for S-Plus or R (http://www.r-project.org), because hand-programming is quite laborious.

I hope you find this helpful, and if you have any questions, please feel free to contact me. Have a good day.

Respectfully,

-- Thomas E. Cason (email)

Response to Sparkline Implementation

Do you have a pdf or simply a screen image of the output?

Thank you for sharing your source code.

-- Jeffrey Berg (email)

Response to Sparkline Implementation

It looks better on paper, I promise :-).

-- Thomas E. Cason (email)

Response to Sparkline Implementation

As for interesting examples, if anyone has a good idea, but not the scripting or illustrating skills, I would consider informal open source cooperative efforts to create proof of concepts. Hit the email link and let me know.

All I ask is that I be able to add the work to my portfolio. I have an example of my code using live data at http://www.pixelplay.org/jeff/sparkline/

-- Jeffrey Berg (email)

Response to Sparkline Implementation

I've had an overwhelming response to my Flash implementation. I simply can't answer all the emails. Here is the source code to my implementation. It uses a model object that is unusual for Flash. I don't recommend it for Flash beginners. If you are new to Flash, take the Flash Lessons found under the help button inside the Flash IDE before attempting this type of Action Script.

You can see that the controller methods are non existent since these graphs are not interactive. The model simply calls the view when it's loaded. Also you could class the whole process properly so you could have multiple instances of graphs in one project. But anyhow, this is a start. The advantage to using Flash for computer generated Sparklines displayed on monitors is the fidelity of vectors. For example, on the Sparkline below right click and select zoom in. You can see it is superior to gif and jpeg pixel aliasing generated by Perl of PHP scripts.

You do need a php proxy script to load the data in if you implement something similar on the web. You'll need to make a "dot" library clip, or replace that line of code with a drawing api function to do the same. The code below is a newer version of the one I've been sending out previously to ask E.T. users.

The Flash example and code:


createTextField("title", 0, 120, 10, 1, 1);
title.autoSize = true;
title._x -= title._width/2;
dataBucket = [];
bucket = new XML();
bucket.ignoreWhite = true;
noCache = new Date().getTime();
bucket.onData = function(str) {
var bucket = escape(str);
bucket = bucket.substring(bucket.indexOf("deg%20F%0A")+10).split("%0A");
for (var a = bucket.length-2; a>=0; a--) {
var t = unescape(bucket[a]).split("   ").join(" ").split("  ").join(" ");
t = t.substring(3, t.length-3).split(" ");
var u = dataBucket[a]=new Object();
u.year = t[0];
u.GMTday = t[1];
u.GMTtime = t[2];
u.aveKts = t[3];
u.gustKts = t[4];
u.direction = t[5];
u.temp = t[6];
}
graphMe();
};
// START INIT
function graphMe() {
var space = 1;
var l = dataBucket.length-1;
var w = l*space;
createEmptyMovieClip("graphholder", 0);
graphholder._y = 30;
graphholder._x = 20;
graphholder.createEmptyMovieClip("graph", 1);
with (graphholder.graph) {
//draw average
beginFill(0xCCCCCC, 40);
moveTo(0, -6);
lineTo(0, -14);
lineTo(w, -14);
lineTo(w, -6);
endFill();
//draw redline
lineStyle(1, 0x990000, 40);
moveTo(0, -_root.dataBucket[0].aveKts);
lineTo(w, -_root.dataBucket[0].aveKts);
//draw spark
lineStyle(1, 0x000000, 80);
moveTo(w, -_root.dataBucket[0].aveKts);
trace(-_root.dataBucket[l].aveKts);
for (var i = 0; i<=l; i++) {
lineTo(w-space*i, (-_root.dataBucket[i].aveKts));
}
}
//create text
outstyle = new TextFormat();
outstyle.font = "Arial";
outstyle.size = 12;
outstyle.bold = true;
outstyle.color = 0x660000;
titlestyle = new TextFormat();
titlestyle.font = "Arial";
titlestyle.size = 12;
titlestyle.color = 0x000000;
graphholder.createTextField("out",0,w+8,-18,100,20);
graphholder.out.autoSize = true;
graphholder.out.text = "Kts: "+_root.dataBucket[0].aveKts;
graphholder.out.setTextFormat(outstyle);
graphholder.out.setTextFormat(0, _root.graphholder.out.text.indexOf(" "), titlestyle);
//create dot
graphholder.graph.attachMovie("dot", "dot", 999);
graphholder.graph.dot._x = w+2;
graphholder.graph.dot._y = -_root.dataBucket[0].aveKts;
graphholder.title.text = "Chicago Wind Data: 3 hours";

}
// END INIT


-- Jeffrey Berg (email)

Response to Sparkline Implementation

I attended Mr. Tufte's presentation in Houston last week and I too was very intrigued by the sparklines representing the season records of sports teams. I run a website which archives sports scores and allows individuals to upload photos which capture the scoreboard displaying the game's final score. Anyways, I took my first shot at implementing dynamic sparklines on my site last night and I would appreciate any feedback anyone is willing to offer.

You may view the most interesting example of these sparklines by...

Thank you in advance for any feedback anyone is willing to offer.

-- Matt (email)

Response to Sparkline Implementation

The sparklines at scoreboardpicts mentioned by Kindly Contributor Matt (above) are delightful. The eye can almost anticipate the flow of outcomes into the future; perhaps the home-game lines can extend into the future.

The sparklines shown are a bit large and will work at about 80% of the size of what is shown. Also the sparklines should be integrated more tightly into the numbers, and the columns of numbers can be more closely spaced.

This is so pleasing, to see sparklines in action.

-- Edward Tufte

Yet another sparkline implementation

I've written a sparkline generator for Photoshop users. It's a Photoshop CS script for Macs & PCs that reads an input data file, creates a new Photoshop document with the sparkline as a path, then "strokes" it (in Photoshop parlance) using the pencil tool. You can control the color and line style by changing the pencil settings. The script prompts you for parameters such as the height of the sparkline (so you can produce higher resolution images for printing on paper, for example), y intercept, and max y value (so you can produce sparklines with a consistent scale).

Example output for a pension fund's cumulative returns:

 Equities 267% Bonds 154%

The web page containing the script and instructions on how to use it is at https://www.lodgephoto.com/articles/sparklines.htm

Regards,

Mathew

-- Mathew Lodge (email)

Response to Sparkline Implementation

Thanks for the feedback. I've added supporting data to the the stock ticker examples as well as larger examples in the spirit of Mariano Belinky's excellent SVG sparklines:

 5-Year Close High Low Cisco 19.55 80.06 8.60 EMC 13.05 101.05 3.83 Sun 5.09 64.32 2.42 Oracle 13.01 43.31 7.32

-- James Byers (email)

Sparkline Implementation: Hi-Res Encapsulated Postscript (EPS) output

Like many on this thread, I recently attended an ET talk and was very interested in learning more about available techniques for generating sparklines. After ET's discussion of the high-resolution capabilities of modern 600-1200dpi printers vs. a normal 'lo-res' computer screen (72-100dpi) I wanted a way to generate high resolution sparklines suitable for printing a group of hi-res 'small multiples'.

After perusing a number of sparkline-related threads on this site and the available technologies (flash, php, etc.) linked from different posts, none of the available solutions seemed to fit the requirements. ET had described how he creates sparklines by first using a graphing package, then massaging in Adobe Illustrator. I figured ET's sparklines ultimately end up as Encapsulated Postscript (EPS) files, so I decided to explore generating sparklines directly as hi-res EPS files.

I was initially concerned about the Postscript printer language, but after some research, the language is quite straightforward and I found a number of helpful examples. Turns out, EPS files are simply text files that are executed by a Postscript interpreter, and are therefore quite simple to generate with any scripting language.

I've included a script written in the Ruby programming language which generates an EPS graphic file of a sparkline from a text input file. Ruby is included in Mac OS X and can be run from the Mac OS Terminal by typing ruby. The code below contains comments describing how it may be used.

In my experiments, I used a sample data file found at the site of Mathew Lodge:

When run, the script outputs a file named ruby.eps which may be viewed with any Postscript viewer, such as the multi-platform Ghostscript or Preview for MacOS X. I've printed the resulting sparkline on my ancient HP Laserjet 4L (300dpi) and, to my eyes, the line is comparable to the sample graphics in the sparklines leaflet I received at the ET talk.

• Sample sparkline (saved as a .PNG screenshot)
• Sample ruby.eps (take a look at this output in a text editor)
• Sample EPS converted to PDF by Mac OS X (try printing this on your printer)

The code below is a rough first cut and still has a number of features missing such as labels, color coding of high/low points, etc. It should give an idea of what is possible in high-res graphing without spending the big bucks on Illustrator and friends. Feel free to use this as a starting point for further explorations.

The Adobe Postscript language reference guide (BLUEBOOK.PDF) was helpful in assembling this script and others may find it useful as well.

#
# Filename: eps_sparkline.rb
# Author:   Dane G. Avilla
#
# Description:
# Assume one argument will be provided: a filename of a text file containing
# a number of positive values to be plotted, one number per line.  Outputs to
# an Encapsulated Postscript file named 'ruby.eps'.
#
#
# Usage: ruby eps_sparkline.rb my_input.txt
#
puts "Processing #{ARGV[0]}"

values = []

# Read the file into the array of values to be plotted, one line at a time.
IO.foreach(ARGV[0]) { |line|
# As long as this line returns a float value, add it to the values.
if(line.to_f != 0.0)
values << line.to_f
end
}

# Get max value to scale graph.
sorted = values.sort
min = sorted.first
max = sorted.last

POSTSCRIPT_POINTS_PER_INCH=72.0

# Setup EPS file.
filename = "ruby.eps"
date = Time.now
init_x = 5
init_y = 0

# Compute scaling.  Currently set to 1" wide, by 1/4" tall.
x_width = POSTSCRIPT_POINTS_PER_INCH
y_width = POSTSCRIPT_POINTS_PER_INCH * 0.25

# Write EPS file.
File.open(filename, File::CREAT | File::TRUNC | File::RDWR) { |file|
file << "%%Document-Fonts: Times-Roman\n"
file << "%%Title: #{filename}\n"
file << "%%Creator: Ruby Script\n"
file << "%%CreationDate: #{date.strftime("%d-%b-%y")}\n"
file << "%%Pages: 1\n"
file << "%%BoundingBox: 0 0 #{x_width} #{y_width}\n"
file << "%%LanguageLevel: 1\n"
file << "%%BeginProlog\n"
file << "%%EndProlog\n"
file << "%% Page:     1    1\n"

# Save the Postscript state.
file << "save\n"

# At this point, scale the image so that it is 1"x.25".
x_scale = x_width / (values.size + 10)
y_scale = y_width / (max.floor + 10)
file << "#{x_scale} #{y_scale} scale\n"

# Move to the initial position and start drawing.
file << "%% Draw the lines of the sparkline\n"
file << "newpath\n"
file << "	#{init_x} #{values[0] - min} moveto\n"

# Create lines between each consecutive point.
values.each_index { |index|
file << " #{init_x + index} #{values[index] - min} lineto\n"
}

# Actually draw the line, and then close out the file.
file << "stroke\n"
file << "restore\n"
file << "%%Trailer\n"
}

Cheers,

-- Dane G. Avilla (email)

Can you recommend a graphing application for producing Sparklines?

Message from Staff - As seen below in the next 11 answers, we've moved another thread on sparkline graphing to this thread.

I'd like to produce sparkline plots for about 250 "nouns" and create a display similar to that reproduced on page 1 of the NYC presentation schedule. I use Delta Graph and would have to do each plot separately and then bring them in individually to a graphics application like PageMaker where they would be matched up with the numeric material.

Too much -- do you have a suggestion for automating the process?

Great presentation

-- Todd Davis (email)

Response to Sparkline Implementation

Even if my version of a sparkline above isn't quite right, Flash is a great medium for sparklines in the event live data needs to be used. If people want more information about where to get started with Flash, email me. I'll be happy to respond with book lists and online Forums to join.

Here is a complete example code that makes a spark line using a static array. See my comments in the code. I think you'll find it's not more difficult than Excel scripts.

//  This is the data set:
array = [20, 23, 85, 98,70, 50, 65, 60,15, 85, 34, 64, 40, 42, 80, 70, 60,55, 71, 65];

//This code sets the thickness, color, and visibility of the line
_root.lineStyle(0, 0x666666, 100);

//This code tells Flash where to start drawing on x and y axis
_root.moveTo(20, 200-array[0]);

//This code is a for loop that draws the line using the data set.
for (var i = 0; i< array.length; i++) {
_root.lineTo(20+(i*20), 200-array[i]);
}

//This code adds the text and positions it at the end of the sparkline.
_root.createTextField("noun", 1, 20+((array.length-1)*20), 200-array[array.length-1], 200, 18);
noun.text = "Noun: " + array[array.length-1];
noun._y -= noun._height/2;


-- Jeffrey Berg (email)

Response to Sparkline Implementation

Dr. Tufte, Your presentation on sparklines in Indianapolis on October 3, 2003, was inspiring. Made me think about this thread. Went home and came up with an implementation for the MLB example, using MS-Excel 200x standard tools (no graphics or charts, no VBA needed). See the following thread Looks great on paper, too. Still have to add the red for shut-outs. Now, we are working on using the concept for a 360 degree employee evaluation reporting tool developed. In particular, we will be adding a small multiple section to the existing reports, that tracks Actual vs Preferred performance over time. Will report back when completed. If anyone has done something similar, using sparklines, I would like to know. Could be a good example for your new book. MANY BLESSINGS! Michael W Cristiani - Market Intelligence Group - http://www.migsite.com

-- Michael W Cristiani - Market Intelligence Group (email)

Response to Sparkline Implementation

Mathematica (Wolfram Research) can generate Sparklines.

Here is some code that produces a graphic that can easily be embedded in a Mathematica text cell. (The graphic has no meaning and is just to demonstrate the technology.) When you embed this in a text cell and print out the notebook, it looks pretty good

Block[{f}, f[x_] = Sin[x] + Cos[8x] + Sin[Cos[4x]]; Plot[f[x], {x, 0, 3}, Prolog -> {GrayLevel[0.7], Rectangle[{0, 0.3}, {3, 1.6}], GrayLevel[0]}, Epilog -> { RGBColor[1, 0, 0], PointSize[0.02], Point[{3, f[3]}], Text[ToString[N[f[3]]], {3, f[3]}, {-1, 0}]}, AspectRatio -> 1/6, ImageSize -> 100, Axes -> False, PlotRange -> {{0, 4}, Automatic}, TextStyle -> {FontColor -> RGBColor[0, 0, 0], FontSize -> 4}]];

-- Seth J. Chandler (email)

Response to Sparkline Implementation

Seth,

The Mathematica code is quite nifty; I removed the grey rectangle and tried a few of my own. Very nice.

Response to Sparkline Implementation

Here are my 2 cents: Using ET-SparkLines directly inside Microsoft-Word through a macro.

Since I do not know how to post pictures in E.Tufte site, you'll find the pictures at http://www.hugonnardfamily.com/ET%2DSparkLines%2DSHB/Compared%20with%20other%20currencies%20v%202004%2012%2012.htm

and the Word file in .doc and .rtf at

http://www.hugonnardfamily.com/ET%2DSparkLines%2DSHB

---- The file without the pictures ----

Examples of ET-SparkLines with S.Hugonnard-Bruyere Word-Macro results

(2004-12-12, after E.Tufte presentation @ Palo Alto last Thursday)

RECAP ON SPARKLINES

As proposed by E.Tufte, the SparkLines represent a compact view of the evolution of a variable, describe a word-like curve: ; the curve is the graphic linear representation of the variable, the min (in blue) and the max (in red) are given.

A SMALL PARAGRAPH EXAMPLE

Compared with other currencies (source http://www.x-rates.com ), the USD Dollar has decreased the last forty days except for the last four days which can also be viewed in inverse graph .

Indeed, compared to Euro, the British Pound, the Yen and the Suisse Franc do not show any special trend:

The same graphs can be zoomed or exported to other applications, since they are mere vector pictures.

In this implementation, I used a concept that was explained by E.Tufte if I correctly understood: keep the focus on the document, and the data attached to it; thus, in this version, the information is kept within the pictures and can be modified directly within Word (through the macro). Even RTF format keeps the information. We can also export the data themselves.

The MACRO is not included in the Word Files but in the Model; anyone with Word (I tested in Word for PC) can read the file, the macro being used for creating and modifying the SparkLines.

More applications to come soon ...

-- S.Hugonnard-Bruyere (email)

Response to Sparkline Implementation

Thomas Cason has contributed a nice LaTeX-pogram to draw sparklines. I was looking for some code that will immediately work with pdflatex. Since there is a package called pgf that also produces the nice beamer file (also mentioned in this forum as an alternative to powerpoint) I thought I could use pgf to provide a package called sparklines. I just uploaded it on CTAN. Unless it is available just do the following: write a file called sparklines.sty containing

\RequirePackage{pgf} \ProvidesPackage{sparklines}
[2005/01/01 v1.0 Sparklines (see more on sparklines at www.EdwardTufte.com)]

% defines sparkline environment
\newenvironment{sparkline}[1]{\begin{pgfpicture}{0ex}{0ex}{#1 ex}{1.75ex}
\pgfsetlinewidth{0.2pt} %line width of 0.2 pt
\pgfsetxvec{\pgfpoint{#1 ex}{0pt}} % says that on unit on the x axes is #1 times the size of x
\pgfsetyvec{\pgfpoint{0pt}{1.75ex}} % says that on unit on the y axes is 1.75 times the size of x
} {\pgfstroke \end{pgfpicture} }

% defines sparkdot with color
\def\sparkdot #1 #2 #3 {%
{\pgfmoveto{\pgforigin}\color{#3}\pgfcircle[fill]{\pgfxy(#1,#2)}{1.2pt}}%
}

% definies sparkrectangle
\def\sparkrectangle #1 #2 {%
{\pgfmoveto{\pgforigin}\color[rgb]{0.9,0.9,0.9} \pgfrect[fill]{\pgfxy(0, #1)}{\pgfxy(1, #2)}}}

% taken from pictex
\def\@shouldIstop#1#2{%
\def\first{#1}%
\def\second{#2}%
\futurelet\nextchar\@testnext}
\def\@testnext{%
\ifx \nextchar /
\let\next=\first
\else
\let\next=\second
\fi
\next}

% defines sparkline-plot
\def\spark #1 #2 {%
\pgfmoveto{\pgforigin} %
\pgflineto{\pgfxy(#1,#2)} %
\@SPARK}
\def\@SPARK#1 #2 {%
\pgflineto{\pgfxy(#1,#2)} %
\@shouldIstop{\pgfstroke\ignorespaces}{\@SPARK}}

and then you can get sparklines like
\documentclass{article}
\usepackage{sparklines}
\renewcommand{\baselinestretch}{1.25}

\begin{document}
\title{Sparklines}

If we want to add a sparkline, be careful not to leave an empty line
between the text left from the sparkline and the environment itself
(starting with the sparkline environment)
% This now starts the sparkline of length 10 times the width of the letter x
\begin{sparkline}{10}
% This environment has now an own coordinate system. x and y run from 0 to 1.

% This draws a sparkling-rectangle with lower level y=0.3 and upper level y=0.5
\sparkrectangle 0.3 0.5

% This draws a blue colored sparkling-dot at x=0.5, y=0.8
\sparkdot 0.5 0.62 blue

% This draws a red colored sparkling-dot at x=1, y=0.2
\sparkdot 1 0.2 red

% draws a sparkline with ten values starting at x=0.1 and y=0.95, then x=0.2 and y=0.8 etc.
% drawing finishes if / appears
\spark 0.1 0.95 0.2 0.8 0.3 0.3 0.4 0.52 0.5 0.62 0.6 0.7 0.7 0.5 0.8 0.4 0.9 0.25 1 0.2 /
\end{sparkline}
Daimler Chrysler, 12\%, {\color{red} 129}, since otherwise the sparkline starts
at a new line.
\end{document}


Just pdflatex the file. Sparklines cannot be seen on a dvi-file, only on a pdffile.

-- Andreas Loeffler (email)

Response to Sparkline Implementation

-- Edward Tufte

Response to Sparkline Implementation

Sparklines implementation for PC Word at

-- Edward Tufte

Response to Sparkline Implementation

Sparklines for a Photoshop script at

-- Edward Tufte

Response to Sparkline Implementation

Problems with several of the implementations of sparklines scattered over all our sparkline threads:

Need to be more thoughtful about aspect ratios (too many very flat sparklines in particular). See page 16 of the chapter:

Sparklines are word-like and typographic. Keep the size and line weights consistent with the local typography. Surround sparklines with type; for example, box-in the sparklines as shown on page 8 of the chapter:

-- Edward Tufte

Response to Sparkline Implementation

In the chapter on sparklines, page 9 shows overlapped sparklines, with up to 10 piled up on each other. See https://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=0001OR&topic_id=1&topic=

It would be a good idea in sparkline code implementations to show at least two overlapped sparklines (in different colors) in the same space.

-- Edward Tufte

Response to Sparkline Implementation

I just went to your seminar yesterday and found that it was full of a world of information that was relevant, clean and concise. I was so energized by the event that when I got home, I began to analyze how to create Sparklines.

I am a graphic designer, so I began to look into other methods of producing outside of true data generators. I found that Adobe Illustrator can create these very easily and accurately. See below for the steps in creating these intriguing Sparklines.

Note: I am using Adobe Illustrator CS on Mac OSX - I am sure that these steps can be recreated on alternate platforms and on older versions of the application.

1. Select your line graphing tool 2. Option click the tool on your page to get a dialog box to specify the size of your graph. 3. Enter all your data in one column. (You can also import data from Excel or any other text file) 4. Once all data is entered, click the checkmark in the upper right of your data table. 5. This will generate your graph. 6. Then, ungroup the graph table. (Note: this will disconnect the data from the graph, so you will not be able to adjust numbers after doing this) 7. Select the Indicator bars to leave just the line. 8. Now you have a true Sparkline that is accurate data. 9. Re-scale, keeping the integrity of the data. 10. Color or add any additional identifiers as well as your text.

This is clean, scalable, simple, accurate and beautiful. By creating these in this format, you have the ability to have total visual control of the outcome while maintaining the integrity of the data. This also allows this method to be enlarged to any size as an object. Who knows, Sparklines can now show up in a tradeshow environment.

Christopher Smith -- Atlanta, Georgia

-- Christopher Smith (email)

Response to Sparkline Implementation

Very clever sparkline constructions in Word True Type fonts at

-- Edward Tufte

Response to Sparkline Implementation

Thought you'd like to see your sparklines in the real world. We will use one on baseball home runs in our paper on Monday, March 21. Seems to be no way to attach it here, but anyone can e-mail me for a copy. We also have one of the "whisker" types completed, but it won't run until fall.

I attended your seminar in Nashville March 4, and was foolish enough NOT to ask you to autograph my copy of your book, but I would appreciate a high-res copy of the Galileo page .. "the earth's annual movement".. if you can send it somehow. And it's NOT for a tattoo, I'll frame it.

You gave a great presentation, and all the designers here are fired up about the sparkline concept. We plan to use more as the opportunity arises, although I can't see them appearing within sentences until we figure out the mechanics of leaving the right amount of space in the text.

Lyn McDaniel, design editor, Huntsville Times, Huntsville, Ala.

-- Lyn McDaniel (email)

Response to Sparkline Implementation

This is great. Please send your sparkline example and the surrounding material to the email marker on our front page; we can then post it. Design at The Huntville Times has scooped design at The Wall Street Journal and the New York Times! Sparklines are a natural for newspapers.

Galielo on the Earth's annual movement is posted on this board at:

https://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=0001dD&topic_id=1

If the resolution is too low, contact Elaine Morse via our email address; she can send a higher resolution version.

Thank you Kindly Contributor Lyn McDaniel.

-- Edward Tufte

Response to Sparkline Implementation

I have used Flint, a tool mentioned earlier in this thread to create a simple sparkline to monitor uptime of a system environment on a live project. I'm currently exporting the uptime as an image from Flint and then embedding in an email to give stakeholders an overview of what's been happening with the system. Here's an example of the simple report I use: Sample Report

It would be interesting to see what members of this board think of it and suggest improvements or provide critique.

-- Lakhdip Nagra (email)

Response to Sparklines: Computer Implementation

Some of the best implementations by Grig Gheorghiu so far at

-- Edward Tufte

Response to Sparklines: Computer Implementation

I just attended the seminar yesterday in Minneapolis. I was intrigued by the sparklines, especially the won/lost sports example. I was able to create this kind of sparkline in JMP.

I am attaching a JMP script that will generate a sample file of MN Twins scores so far this year. I doctored the scores of 2 games to offer a few shutouts. There is a script to generate the graphic. Using the selection tool in JMP, copy just the graphic portion of the plot and paste it into Word as a picture. Crop the graphic in Word about 0.03" on all sides and resize (40% worked for me) and you have a word-sized graphic.

It's not the most elegant, but I was able to do this in about 30 minutes of work. I could script it better to automate some of the data editing I had to do, but for now, this will work pretty well.

I could post the actual graphic if someone could tell me how to post graphic images on this board.

The JMP script is below. Copy it into a JMP scripting window and run it.

New Table("Twins won lost", Add Rows(70), New Property("Sparklines", Overlay Plot(X( :New Date), Y( :Shutouts Yes, :Shutouts No), X Axis << {Scale(Linear), Format(m), Min(3195331200), Max(3197404800), Interval(Day), Inc(3)}, Connect Points(1), Show Points (0), :Shutouts Yes(Show Points(0)), :Shutouts No(Show Points (0),Connect Color(0)), SendToReport(Dispatch({}, "101", ScaleBox, {Scale(Linear), Format(m), Min(3195331200), Max(3197404800), Interval (Day), Inc(3)}), Dispatch({}, "Overlay Plot", FrameBox, Frame Size (129, 39))))), New Column("Date", Numeric, Continuous, Format ("m/d/y", 10), Set Values ([3195417600,3195417600,3195417600,3195417600,3195504000,3195504000, 3195504000, 3195590400,3195590400,3195590400,3195676800,3195676800,3195676800, 3195763200,3195763200,3195763200,3195849600,3195849600,3195849600, 3195936000,3195936000,3195936000,3196022400,3196022400,3196022400, 3196108800,3196108800,3196108800,3196195200,3196195200,3196195200, 3196281600,3196281600,3196281600,3196368000,3196368000,3196368000, 3196454400,3196454400,3196454400,3196540800,3196540800,3196540800, 3196627200,3196627200,3196627200,3196713600,3196713600,3196713600, 3196800000,3196800000,3196800000,3196886400,3196886400,3196886400, 3196972800,3196972800,3196972800,3197059200,3197059200,3197059200, 3197145600,3197145600,3197145600,3197232000,3197232000,3197232000, 3197318400,3197318400,3197318400])), New Column("Won_Lost", Character, Nominal, Width(16), Set Values ({"", "L", "", "", "W", "", "", "W", "", "", "", "", "", "L", "", "", "L", "", "", "W", "", "", "", "", "", "W", "", "", "W", "", "", "W", "", "", "W", "", "", "W", "", "", "L", "", "", "L", "", "", "L", "", "", "W", "", "", "W", "", "", "L", "", "", "", "", "", "", "", "", "L", "", "", "W", "", ""})), New Column("WL_0_1", Numeric, Continuous, Format("Best", 10), Set Values( [.,-1,.,.,1,.,.,1,.,.,.,.,.,-1,.,., -1,.,.,1,.,.,.,.,.,1,.,.,1,.,.,1,.,.,1,.,.,1,.,.,-1,.,.,-1,.,., -1,.,.,1,.,.,1,.,.,-1,.,.,.,.,.,.,.,.,-1,.,.,1,.,.])), New Column("Location", Character, Nominal, Width(16), Set Values ({"", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Home", "Home", "Home", "Home", "Home", "Home", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away", "Away"})), New Column("Home W/L", Numeric, Continuous, Format("Best", 10), Formula(If( :Location == "Home", :WL_0_1, Empty()))), New Column("Away W/L", Numeric, Continuous, Format("Best", 10), Formula(If( :Location == "Away", :WL_0_1, Empty()))), New Column("T Score", Numeric, Continuous, Format("Best", 10), Set Values ([.,0,.,.,8,.,.,4,.,.,.,.,.,1,.,.,5,.,.,5,.,.,.,.,.,5,.,.,8,.,.,10,., .,3,.,.,6,.,.,1,.,.,4,.,.,1,.,.,5,.,.,10,.,.,4,.,.,.,.,.,.,.,.,4,.,., 2,.,.])), New Column("O Score", Numeric, Continuous, Format("Best", 10), Set Values ([.,5,.,.,4,.,.,1,.,.,.,.,.,5,.,.,8,.,.,0,.,.,.,.,.,4,.,.,4,.,.,4,., .,2,.,.,4,.,.,2,.,.,5,.,.,3,.,.,4,.,.,9,.,.,5,.,.,.,.,.,.,.,.,6,.,., 1,.,.])), New Column("Shutouts", Numeric, Continuous, Format("Best", 10), Formula(If(( :T Score == 0 | :O Score == 0) | Lag( :T Score, 1) == 0 | Lag( :O Score, 1) == 0, 1, Empty()))), New Column("Won Lost", Numeric, Continuous, Format("Best", 10), Formula(If(!Is Missing( :WL_0_1), :WL_0_1, Is Missing( :WL_0_1) & !Is Missing(Lag( :WL_0_1, 1)), 0, (Is Missing( :WL_0_1) & Is Missing(Lag( :WL_0_1, 1))) & :Location == "Home", 0, Empty()))), New Column("New Date", Numeric, Continuous, Format("m/d/y", 10), Formula(If(!Is Missing(Lag( :Won_Lost, -1)), Lag( :Date, -1), :Date))), New Column("Shutouts Yes", Numeric, Continuous, Format("Best", 10), Formula(If( :Shutouts == 1, :Won Lost, Empty()))), New Column("Shutouts No", Numeric, Continuous, Format("Best", 10), Formula(If(Is Missing( :Shutouts), :Won Lost, Empty()))));

-- Bruce White (email)

Response to Sparklines: Computer Implementation

Reading the responses on this board made me think about how I could implement sparklines in my field. I think all of the code and samples presented so far use Sparklines in a static, or at least slow-moving, display. I develop user interfaces for quality controls systems in the packaging industry. We monitor carton production at high speeds (over 200,000 cartons/hr).

My idea was to use them for a high-speed process, like so:

This packs a lot of information into just 297x20 pixels (less than 1% of our screen real estate). The small scroller shows the last 50 units, the current speed, and which units were failures. I think it could be easily expanded to include other information as well.

-- Dan McCarty (email)

Apple's Quartz Composer Imaging Software

Apple's latest version of its OS X operating system, 10.4 ("Tiger"), includes a new tool that may be of value to this community. It is an application called "Quartz Composer" included as part of the optional Developer's Tool installion package.

Apple's developer's documentation describes the application as, "a development tool provided with Mac OS X v10.4 for processing and rendering graphical data." While a programming background may be necessary to truly tap the power of this tool, Apple's documentation promises that people can "create compositions that process graphical content without writing a single line of code."

Quartz Composer is a decendant of an application called PixelShox, whose developer has stopped working on the project. Quartz Composer is being touted as means to showcase the underlying power of the new graphic foundation with in the OS. Early users are already creating websites and distributing sample files, and one enthusiastic blogging developer writes, "In my twenty-five years of hacking on computers Quartz Composer may be the most fun environment I've experienced yet." Another person on the same page comments, "Amazing tool...already using it to develop my psychophysics experiments and playing with it just for fun....from the engineering perspective, you can use this to develop dynamic simulation models of various sorts." (http://weblog.decentric.com/home/2005/02/quartz_composer.html).

Quartz Composer enables the developer to combine images and almost any kind of data: audio and MIDI, video, XML, live internet feeds (such as RSS), time values, etc. The resulting "compositions" can be played back through the operating system (such as screen savers), viewed by QuickTime, or act as stand-alone products.

The system requirements are pretty heavy: you need 10.4 and a modern Mac with a good video card. The newest Mac hardware should all be compatible, but machines a few years older may not be powerful enough to render the compositions.

http://developer.apple.com/documentation/GraphicsImaging/Conceptual/QuartzComposer/index.html

http://quartzcomps.com/

http://www.vjcentral.com/news/view/id/quartz_composer_on_os_x_tiger

Cheers,

Jim

(Note: An existing Windows music application also called QuartZ Composer, is similar to Apple's Garage Band. Don't be surprised if Apple is forced to change the name of this new tool.)

-- Jim Williamson

Response to Sparklines: Computer Implementation

I've got a new post of an example of a sparkline using Microsoft's next presentation language called XAML. It is vector based so it scales nicely, just like SVG. Here's a screen shot.

And here's the link to my blog entry. http://dotnetjunkies.com/WebLog/metablog/archive/2005/05/10/74527.aspx

-- Sean Gerety (email)

Response to Sparklines: Computer Implementation

Regarding the simple animation I posted above, I've had a chance to clean it up a bit. I don't know Flash very well, but I have had some experience with Director. (Unfortunately, this page might now ask you to install Shockwave to view the animation. I recommend installing it, if you haven't already.)

The new animation looks like this:

(If you aren't seeing a blue horizontal line with cartons scrolling from right to left try clicking this link.)

• I changed the width of the object so that it's a scaled representation of the length of the entire machine.
• The small ticks along the line represent where a scanning station resides on the machine.
• As the cartons pass a scanning station, they have a chance of failing (and they typically fail in batches)

I realize that this isn't a strict implementation of a sparkline. There's not even any "sparkiness." But I think that it's a powerful visual for a sparkline with rapid changes, as opposed to a static one in newsprint.

This could also be extended to show some information along the y-axis as well. For example, if we were doing bar code grading, we could show "good reads" high, "no reads" middle, and "bad reads" low.

-- Dan McCarty (email)

Response to Sparklines: Computer Implementation

Dan It seems that the space in the lower right hand portion of the drawing could be better used.

Have you considered any statistics such as the track speed or failure percentage

It would also be interesting to know the failures by scanner and if the scanners are the same why are they not failing on each one? Are they looking for different qualities? How do I tell if I have a faulty scanner?

Are the widgets sensitive to environmental factors?

-- Joe Bronson (email)

Response to Sparklines: Computer Implementation

Joe: - The -/+ buttons are just in the demo to show what it looks like at different speeds. The actual size of the control is 640x23, which is less than 2% of our available screen real estate (running at 1024x768).

- Machine speed, measured in ft/min or m/min is being reported on another area of the screen in big, 1" numbers. Failure percentage is a useful metric on our data collection product, but probably not as useful on the machine itself.

- Yes, the scanning stations are always scanning for different qualities, which is why some cartons fail at some scanning stations and some fail at others.

- And lastly, yes, the widgets can be sensitive to humidity (in the cardboard and glue), although it's not something we usually scan for.

-- Dan McCarty (email)

Response to Sparklines: Computer Implementation

I have tried to come up with some code to display a sparkline in Excel. What I developed is a class module where I define the sparkline data, height, width, and starting point. Then one would call the Generate method, and the sparkline is displayed using the Excel/MS office freeform drawing tool. The result is a line graph, which can be defined, for example, to be as big as one cell. There is no error checking yet.

I am still thinking to implement a "whisker" type graph.

Ok, in the class module called "Spark", I have:

'-----------------------------------------
Option Explicit
Private varData As Variant
Private BeginX As Double, BeginY As Double
Private dblW As Double, dblH As Double

Property Set Datapoints(ByVal r As Range)
Dim C As Range, i As Long, D() As Double
ReDim D(r.Cells.Count)
i = 0
For Each C In r.Cells
If IsNumeric(C.Value) Then
D(i) = C.Value
i = i + 1
End If
Next C
varData = D
End Property

Property Let StartingPointX(ByVal X As Double)
BeginX = X
End Property
Property Let StartingPointY(ByVal Y As Double)
BeginY = Y
End Property

Property Let Width(ByVal w As Double)
dblW = w
End Property

Property Let Height(ByVal h As Double)
dblH = h
End Property

Sub Generate()
Dim i As Long, n As Long, min As Double, max As Double, xScale As Double, yScale As Double
min = varData(0)
max = varData(0)
n = UBound(varData) - 1
For i = 0 To n
If varData(i) < min Then min = varData(i)
If varData(i) > max Then max = varData(i)
Next i
xScale = dblW / n
yScale = dblH / (max - min)
With ActiveSheet.Shapes.BuildFreeform(msoEditingAuto, BeginX, BeginY - (varData(0) - max) * yScale)
For i = 1 To n
.AddNodes msoSegmentCurve, msoEditingAuto, BeginX + i * xScale, BeginY - (varData(i) - max) * yScale
Next i
.ConvertToShape '.Select
End With
End Sub
'-----------------------------------------

A sparkline would then be generated with the following code, for example:

'-----------------------------------------
Sub MakeSparks()
Dim s As New Spark, r As Range
Set r = Selection
s.StartingPointX = r.Left
s.StartingPointY = r.Top - r.RowHeight
s.Width = r.Width
s.Height = r.RowHeight
Set s.Datapoints = r
s.Generate
End Sub
'-----------------------------------------

The user can select a column of data and run MakeSparks, and the sparkline is generated in the cell right above the column.

Suggestions are welcome!

Cheers,
Sjoerd

-- Sjoerd Hoogwater (email)

Response to Sparklines: Computer Implementation

To create a sparkline in Excel is easy with no coding.

You can either use the camera tool, or create a picture link. I have been using this method to create sparklines for daily reports for several months. Once created in Excel, they update automatically and are linked to a daily email I send. It is important to begin with a large chart that is simple enough to look good when resized. Once the linked picture has been created following the directions below, resize it to fit a line of your text.

The following is based on information I found on j-walk.com at http://j-walk.com/ss/excel/odd/odd04.htm :

The Camera tool, a toolbar button with an image of a camera, does not appear on any of the built-in toolbars. You can add it to a toolbar, though. You'll find it in the Tools category of the Customize dialog box. It's description is as follows:

Camera: Takes a linked picture of the current selection and pastes it in a new location. The picture is linked by a formula that refers to the copied cells, so it is updated when the copied cells change. Click the Camera button to take the picture, and then click where you want to paste the upper-left corner of the selection.

Even if the Camera tool is not on a toolbar, you can get exactly the same effect by following these steps:

1. Select the range. This is not the chart itself, but the cells behind the chart. The chart will show up in your picture.

2. Choose Edit - Copy

3. Press the Shift key and choose Edit - Paste Picture Link (this command is available only when the Shift key is pressed).

4. The result is a linked picture of the original range. You can move this picture anywhere you like and resize it down to fit a single line of text.

I did this several month ago, creating several long narrow charts and shrinking them to fit inside a table of daily statistics which is linked to a daily email. The only maintenance has been to update the background data.

-- Doug Horton (email)

Response to Sparklines: Computer Implementation

All sorts of interesting implementations (and code) at

-- Edward Tufte

Response to Sparklines: Methods of computer code implementation

I have written a very simple sparkline plugin for the Wordpress blog platform. It uses James Byers' sparkline PHP library. On Javascript enabled browsers it can scale the graph to match the text size.

-- Graeme Pietersz (email)

Response to Sparklines: Methods of computer code implementation

Ruby on Rails is a web framework based on the programming language, Ruby. It's gaining popularity becuase the language is so well thought out, clean, and simple. http://www.rubyonrails.com/

Recently a Sparklines Graph Library was released for Ruby: http://nubyonrails.topfunky.com/articles/2005/07/28/sparklines-graph-library-for-ruby

Like most things ruby, it's VERY easy to implement, and requires minimal coding.

-- Dave Tufts (email)

Response to Sparklines: Methods of computer code implementation

HI all,

Yet another implementation of sparklines. This time, however, there is no image generation at all. In this one, I used only CSS and XHTML. In fact, I have started a blog about the use of web standards for quantitative data visualization (http://datawisualizing.blogspot.com).

You can see the implementation of the sparklines here. Comments can be posted here and/or directly in the blog.

Best,
Marc

-- Marc Marti-Renom (email)

Response to Sparklines: Methods of computer code implementation

Mark, your sparkline looks ok in FF1.5 but not in IE6. You might want to check your xhtml/css against w3.org validators.

-- Simon Shutter

Response to Sparklines: Methods of computer code implementation

Marc, I like the idea. It should be easy enough to write scripts that will generate the graph HTML from continuously updated databases. It will need a Bizzantz-style GUI for manual data entry, including auto-ranging. However, a CSS implementation may be the most elegant idea yet.

-- Niels Olson (email)

Response to Sparklines: Methods of computer code implementation

Hello: Just found this blog post about a forthcoming BBC online archive "It turns out there's a huge database that's been carefully tended by a gang of crack BBC librarians for decades. Nearly a million programmes are catalogued, with descriptions, contributor details and annotations drawn from a wonderfully detailed controlled vocabulary. I'm the lucky developer who gets to turn this hidden treasure into a public website. No programme downloads yet, but a massive searchable programme catalogue."

Image with sparkline: http://www.hackdiary.com/images/peel-contrib.png

Cheers,

Jim

-- Jim Williamson (email)

Response to Sparklines: Methods of computer code implementation

I'm looking to use sparklines in Excel. I have downloaded Sparkmaker from Bissantz, and have used it successfully, but I can't figure out how to replicate it for many different sparklines. I would like to make 80 different sparklines of 10 observations each. I have all of my data in a spreadsheet.

Must I go line by line and paste my data into the Sparkmaker window, choose my formatting, select the destination cell, and click insert for all 80 sparklines?!?

As you can see, I'm not a programmer, so any step-by-step help (in creating a macro or some other process) will be greatly appreciated.

Thanks, Brett

-- Brett (email)

Response to Sparklines: Methods of computer code implementation

Brett, the idea is that the Excel implementation of the sparklines concept can be packaged as an Excel add-in, which is attached to any spreadsheet you have that needs sparklines. That saves you the cut-and-paste effort.

I have need for such a tool and am implementing it now, though someone else may be way ahead of me. I'll try to remember to post a notice here when I'm done with it.

-- Oscar Gunther (email)

Response to Sparklines: Methods of computer code implementation

Here is the first version (hopefully of many) of an automated MS Excel implementation: http://www.sparklinesXL.com/. Download the self-extracting zip file and read the PDF for further installation instructions.

-- Bill Pfister (email)

Response to Sparklines: Methods of computer code implementation

I have written a macro for Excel that draws a sparkline chart. The macro scans column A for the start value, end value, highest value and lowest value. Then it draws a chart with no borders or axes, properly scales the chart for the space, colors the first and last values blue, colors the highest and lowest values red, and colors the data line black.

This chart is perfect for insertion into a Word (or other) document.

I would be pleased to send the Excel spreadsheet containing the macro code plus detailed instructions on how to run the code and insert the sparkline into a word document to anyone who requests it.

Please email me at ronblack@calweb.com and put "sparklines" in the subject, and I will send you the file.

Happy charting...Ron Black

-- Ron Black (email)

Response to Sparklines: Methods of computer code implementation

It would good if our Kindly Contributors could show some sample output of sparklines based on their code.

Thanks,

ET

-- Edward Tufte

I apologize for the delay, but I have enabled the download for the Microsoft Excel add-in again. Please let me know if you have any questions or suggestions.

Bill

http://www.sparklinesXL.com/

-- Bill (email)

We are tickering sparklined stock quotes on our website.

The ticker here is live too and shows daily updated Dow Jones quotes for a period of 60 days (blue band = 1 std dev). Every sparkline is scaled individually, hence look at min/max values when reasoning about volatility.

Please feel free to use the ticker on your site, two HTML tags will do. Our server takes care of the sparkline production.

<marquee scrollamount="1" scrolldelay="5"><img src="https://www.bissantz.de/sparkserver/images/ticker-dj.png" height="20"></marquee>

Currently leading in sparklined tickers is Spain, with three portals so far: Kuvet, IS-Portal and MundoBI.

Olé!

-- Nicolas Bissantz (email)

It might to useful to reduce the length of the horizontal stretch slightly, in order make the lines more lumpy rather than quite so flat. Of course, you'll want to average over all the lines to decide the ideal aspect ratio. At the end of the sparkline essay, there's a discussion of aspect ratios; choose the aspect ratio to yield lumpy lines, not too spike-like and not too flat.

-- Edward Tufte

I think some progress could be made on the typography. Try Verdana or Gill Sans adjusted for computer screen. The color links are a bit unclear to me. And can we do better than the pipe symbol? How about an arrowhead on the pipe symbol if that symbol is necessary? Are the brackets doing anything for us? In general, every single visual move should carry data. So try to eliminate all framing, all non-data elements, just like sparklines do.

-- ET

Is the bar representing +/- 1 standard deviation necessary? Or at least possible to be turned off? I find it somewhat distracting visually. Also a setting for the use of a comma or period to represent the decimal point.

One could question the meaning of a standard deviation when applied to a stock price. Most plotting programs for stock data simply have an 'n' period moving average as even an average price has little meaning.

-- Andrew Nicholls (email)

Another minor question on the stock price standard deviation illustration as well is whether it is appropriate to show it in these terms or in log terms, given that the assumption for stock price behaviour in Black-Scholes is for lognormally distributed prices. Anything derived from the options market for confidence intervals looking forward in time would make this assumption

-- Will Oswald (email)

I have a sparkline implementation for IDL (Interactive Data Language) available at my website. There are options to control the colors, scaling, and normal band range. For an example, here is a sparkline of the high temperatures for the last 28 days in Boulder 55 degrees F.

-- Michael Galloy (email)

The poor season-opening performance of the Kansas City Royals had me looking back over the last quarter-century to see losing streaks, seasonal performances, etc.

The result was the following sparkline example:

-- Michael Round (email)

See also the Sports Graphics: excellent sparklines thread. The Hardball Times has a sparkline generator at: http://www.hardballtimes.com/thtstats/main/sparklines/custom.php

-- Michael (email)

I've created the PHP code necessary for the bivariate primary variable sparkline, i.e. the "baseball" line. This code will dynamically produce sparklines based on data entered into a MySQL table called "sparklines" with the columns "ID" (auto-increment, INT(3)), "win" (INT(1), 0 or 1) and "home" (INT(1), 0 or 1). The only image necessary is a 1x1 spacer for browsers that won't accept empty table cells, which is placed in a folder called "images" off the root folder.

The result is a sparkline made entirely of HTML table elements that will fit inline (without affecting line spacing) of most 13px web text, like so:

The code is as follows, and you can visit http://www.webofdc.com/offsite/sparklines.php to see it implemented w/ some surrounding text.

  <table style="display: inline; height: 7px" cellpadding="0" cellspacing="0" border="0">     <tr>     <code> <?  $dbc = mysql_connect ('address','username', 'password'); mysql_select_db ('database');$query = "SELECT ID, win, home FROM sparklines ORDER BY ID"; $r = mysql_query ($query); $count=mysql_num_rows($r)*3; //row for wins while($row = mysql_fetch_array($r)) { echo "<td width='1' height='4' bgcolor='#ffffff'><img src='images/spacer.gif' width='1' height='1'></td><td width='1' height='4' bgcolor='#"; if ($row['win']==1) { echo "000000";} else { echo "ffffff";} echo "'><img src='images/spacer.gif' width='1' height='1'></td><td width='2' height='4' bgcolor='#ffffff'><img src='images/spacer.gif' width='1' height='1'></td>\n"; } echo "</tr>\n"; // optional blank row /* echo " <tr>\n <td colspan='{$count}'><img src='images/spacer.gif' width='1' height='1'></td>\n       </tr>\n */ // row for home/away echo "<tr>\n"; $query = "SELECT ID, win, home FROM sparklines ORDER BY ID";$r = mysql_query ($query); while($row = mysql_fetch_array($r)) { echo "<td width='3' colspan='3' height='1' bgcolor='#"; if ($row['home']==1) { echo "000000";} else { echo "ffffff";} echo "'><img src='images/spacer.gif'></td>\n"; } echo "</tr>\n"; // optional blank row /* echo "       <tr>\n           <td colspan='{$count}'><img src='images/spacer.gif' width='1' height='1'></td>\n </tr>\n */ // row for losses echo "<tr>\n";$query = "SELECT ID, win, home FROM sparklines ORDER BY ID"; $r = mysql_query ($query); while($row = mysql_fetch_array($r)) { echo "<td width='1' height='4' bgcolor='#ffffff'><img src='images/spacer.gif' width='1' height='1'></td><td width='1' height='4' bgcolor='#"; if ($row['win']==0) { echo "000000";} else { echo "ffffff";} echo "'><img src='images/spacer.gif' width='1' height='1'></td><td width='2' height='2' bgcolor='#ffffff'><img src='images/spacer.gif' width='1' height='1'></td>"; } ?> </tr> </table>  Hope someone can make use of this. I'll work on a version for the multivariate primary variable sparkline. -- Jeremy B. Lupoli (email) Can we see some examples of data input and what is then returned graphically? -- Edward Tufte I've now completed the interval level sparkline code for PHP as well. Marc's problem above with IE was that it needs SOMETHING, even if it's a 1x1 transparent image, in each DIV or it won't render correctly. Code, testing, and output are available at http://www.webofdc.com/offsite/sparklines.php. Not bad for just learning about sparklines at my course today huh?! -- Jeremy B. Lupoli (email) Tighten up the X dimension a lot and the Y dimension somewhat. That will improve the aspect ratio (lines are too flat) and turn them into sparklines. Then distribute similar on a map for different places over the country. -- Edward Tufte I just completed a bare-bones Java (along with a JSTL taglib) implementation at: http://www.representqueens.com/spark/. It currently only supports bar and line graphs, and the documentation is a little scarce, but I'm anxious to share it and I think that it's pretty usable. I'll try to add some more detailed documentation, examples, and source code in the next couple of weeks. I'd appreciate any comments, suggestions, criticism, etc. thanks. -- larry (email) Ramana Rao and Stuart Card, from Xerox PARC, have invented something they call TableLens, which appears to be a spreadsheet shrunk down into nothing but columns and columns of sparklines. The rectangle of more conventional-looking spreadsheet cells in the middle is presumably a "magnifying lens" you can move over the data to examine areas of interest. Rao explains his concept here. He cites Lotus Improv (which I was disappointed never took off), John Tukey, and Jacques Bertin as inspirations. -- Derek Cotter (email) With regard to computer displays, the obvious challenge in tightening up the x axis is that a data point is necessarily a pixel, of which you have either 72 or 96 per inch, correct? Using vectors (svg and such) allows you to 'spec' sub-pixel data points i suppose, but then the implications of aliasing arise. Even in print, I imagine you wouldn't want a data point with less width than .25 pt which would yield no more than 288 points (rounding to 72 pt/inch in our postscript age). I'm ignoring here the question of the appropriateness of an inch-long sparkline. It feels like there may be a formula here, or some good rule-of-thumb ranges for us to follow? -- LeMel I check in on this thread from time to time and I would like to know why none of the implementations to date produce output identical to the sparklines presented in "Beautiful Evidence". I am not putting down any implementation, so please do not take this as a slam. You all work hard on these implementations and I applaud the work you're doing. I have tried several of the tools mentioned here and they all produce good results, but they do not give me output close enough to that shown in the book. I would like to understand the challenges better because I work in a large IT shop with hundreds of developers. I may be able to tap into that resource to advance the cause. E.T.: I'd like to know the workflow from data set to analysis to interim graph to Illustrator to final product. Is that something you can share? Until a software approach can produce what I see in "Beautiful Evidence" I would like to try doing it your way. Terrence Randell -- Terrence Randell (email) New Page 1 I want to share with you a smart way to create sparklines with Excel, just using the Excel on-board tools. The only requirement is that you have Excel 2000 or higher installed. 1.) Enter 12 positive values in the range A1:L1. 2.) Enter the formula =A1/MAX($A$1:$L$1) in the cell A2 and copy the cell to the cells B2:L2. 3.) Assign the name 's' to the range A2:L2. 4.) Enter the following formula into the cell M1. =CHOOSE(INDEX(s,1)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,2)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,3)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,4)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,5)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,6)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,7)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,8)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,9)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,10)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,11)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█")&CHOOSE(INDEX(s,12)*8+1,"▁ ","▁ ","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█") 5.) Format the cell M1 with the font 'Arial Unicode MS'. Voila a nice column sparkline. Its not comparable to the quality of SparkMaker or MicroCharts but its for free and with a little tweaking you can get quite nice results. Have fun Andreas Flockermann BonaVista Systems -- Andreas Flockerman (email) Andreas, it's nice, but the most frustrating feature for me is that the "zero" value defaults to one. That's not your fault, but a stunning lack of foresight by the designers of the Arial Unicode MS font, who provided a myriad of different space widths, not a single one of which matches the 1/8 height vertical block set. In other words, they have provided a nine level system of blocks (0-8) with the zero missing! I'm also frustrated by that missing space value because it makes it very difficult to do anything useful with the line characters, like draw borders. -- Derek Cotter (email) For those interested in creating sparklines from Excel, see my post on May 19, 2005. Any type of chart Excel can create can become a sparkline. Just be careful to keep it simple and readable. I have been creating sparklines daily quite easily for almost two years now. -- Doug Horton (email) Amarok is free music player for Linux, like itunes, but more robust. One feature calculates a "moodbar" for each track by computing a fast Fourier transform! In the screenshot below Beethoven's sonatas are arranged by mood. Redder is lower frequency, darker indicates higher amplitude. In the lower right the current track's mood bar is recapitulated with a pointer indicating where you are in the music; one quickly gets a sense of what is coming. My only want is that they should be displayed on a constant time scale. There is another sparkline on the left showing CPU usage history. Having a context window for the artist's Wikipedia page is nice too. -- Niels Olson (email) Sparklines in LaTeX The methods described above for producing sparklines in LaTeX both require either typing the data into the document or inventing some script to do so, which is tedious and error-prone and has kept me from using them. The trouble with free tools is that each is only good at one thing, and you have to daisy-chain them together. However, I've finally managed to produce some sparkline-like graphics directly from an analysis tool. The chain of tools is • Octave for numerical analysis, which uses • Gnuplot for data display. One of gnuplot's output formats is for • Xfig, a vector graphics program which can produce output parseable by LaTeX, and importantly • latex-make, which automates the maintenance of LaTeX documents composed of multiple files. (Gnuplot can produce LaTeX output directly, but there's no graphical editor for tweaking the plot without replotting all the data.) Here's a simple example. In some directory (e.g. ../sparkline-example/) create a file Makefile containing default : example.pdf include LaTeX.mk and a file example.tex containing \documentclass{article} \usepackage{texdepends,figlatex} \usepackage{graphicx} \begin{document} Here is some meaningless sentence so that the below comes mid-paragraph. The first ten pulses recorded by the summing amplifier, \includegraphics[height=2ex]{sumamp.fig}, display striking monotony. Here is some meaningless sentence so that the above comes mid-paragraph. \end{document} Now, in octave, octave> plot(tof10(:), sums10(:), "@;;") # plot your data using points; no title; octave> __gnuplot_set__ border 0 lw 0 ; replot # turn off the border octave> __gnuplot_set__ noxtics ; __gnuplot_set__ noytics ; replot # no tic marks octave> __gnuplot_set__ size ratio 1.0/12 ; replot # make it long. At least one of these numbers must have a stupid decimal point octave> __gnuplot_set__ pointsize 0.1 ; replot # the default markers are too big octave> print("../sparkline-example/sumamp.fig","-dfig") ; system("make -C ../sparkline-example"); # do the conversion to .pdf The output appears in "example.pdf", which is attached. I'm experimenting with using sparkline-like plots grammatically the same way as mathematical symbols. One page of an attached experiment is "page.pdf". Each of the three figures shown represents about 10^6 numbers, though only 10^3 are plotted. Advice? -- Rob Mahurin (email) Any Excel code (or other code) for sparklines on Mac? -- David Passmore (email) Hi, I'm a developer for a site called EveryBlock, which just launched yesterday, that filters local news and public information by geography so users can better understand what's happening at the block, neighborhood, and city level. I thought you and the forum readers might be interested in our take on sparklines, which we use in a number of instances across the site for display aggregate statistics about the various types of data we're collecting. For instance, here is a list of crime statistics by neighborhood in Chicago for the last 30 days: http://chicago.everyblock.com/crime/locations/neighborhoods/ On the main Chicago crime page, we use slightly different sparkline formulations for the city-wide stats, and for the crimes broken down by various categories: http://chicago.everyblock.com/crime/ Readers may be interested to know that we used web standards -- regular HTML markup and CSS stylesheets -- to achieve these displays. They aren't images or Flash or other technologies. They're also "semantically-rich": in other words, if you do a "view source" on the HTML, you can see the individual data points for each statistic (also viewable if you disable styles in your browser). This allows users of the site to get both the visual view of the data in a compact and efficient way and also drill-down into the raw data points if they wish to investigate further. -- Paul Smith (email) Here is a simple R implementation of sparklines. Running sparkline() will generate a random sparkline; running sparkline(yourdata) will generate a sparkline using the data in yourdata. As an example, here is Google's stock price for the last year. #R sparklines sparkline<-function(ydata=rnorm(100,500,50),width=1.5,height=0.5,sigfigs=4) { # ydata = vector of data to be plotted # width = width of sparlkline in inches, including text # height = height of sparkline in inches # sigfigs = number of significant figures to round min, max, and last values to temppar<-par(no.readonly = TRUE) # store default graphics parameters par(mai=c(0.10,0.05,0.10,0.05),fin=c(width,height)) # adjust graphics parameters for sparklines len<-length(ydata) # determine the length of the data set ymin<-min(ydata) # determine the minimum tmin<-which.min(ydata) # and its index ymax<-max(ydata) # determine the maximum tmax<-which.max(ydata) # and its index yfin<-signif(ydata[len],sigfigs) #determine most recent data point plotrange=c(ymin-0.3*(ymax-ymin),ymax+0.3*(ymax-ymin)) # define plot range to leave enough room for min and max circles and text plot(x=1:len,y=ydata,type="l",xlim=c(1,len*1.5),ylim=plotrange,col="gray",lwd=0.5,ann=FALSE,axes=FALSE) # plot sparkline points(x=c(tmin,tmax),y=c(ymin,ymax),pch=19,col=c("red","blue"),cex=0.5) # plot min and max points text(x=len,y=ymin,labels=signif(ymin,sigfigs),cex=0.5,pos=4,col="red") # show minimum value text(x=len,y=ymax,labels=signif(ymax,sigfigs),cex=0.5,pos=4,col="blue") # show maximum value text(x=len,y=(ymin+ymax)/2,labels=yfin,cex=0.5,pos=4) # show most recent value par(temppar) # restore graphics defaults }  -- Jason Dieterle (email) Response to Response to Sparklines: computer code implementation Hi Jason, I just wanted to thank you for your code, which I've used and cited in a discussion at stackoverflow on making sparklines with R. Your annotation is much appreciated! Here's the further discussion, the main extension of your method is creating a panel of multiple sparklines, rather than just individual ones as your code does: -- Ben (email) A List Apart, the delightful online magazine for web developers, just posted an article on "Accessible Data Visualization" by Wilson Miner, the designer of EveryBlock. The article describes how to publish data sets so that the underlying numbers are preserved accessibly in the page content, yet show up in a normal browser as a sparkline. The entire article should interest any web content producing readers here, but http://alistapart.com/articles/accessibledatavisualization#sparklines will take you straight to the section about sparklines. -- Nathan Vander Wilt (email) The Google Charts API now makes it easy to include sparklines in custom web applications. You essentially create a URL that includes the data to be graphed, and when the browser requests the URL from the Google chart server, an image containing the appropriate sparkline is returned. However, when developing web pages that included sparklines, I ran into an additional wrinkle -- pages that contained lists of elements with attached sparklines frequently loaded hundreds of images. Because serial HTTP GET requests are very expensive, rendering performance could suffer noticeably in sparkline-rich pages. When researching the problem, I discovered a little-used web construct called "data" URLs. Data URLs allow the inline embedding of a resource directly into the web page, eliminating the need for the additional external request per resource. They're little used because they're impractical for encoding anything but very small amounts of data. A sparkline being a very small amount of data that should be rendered inline with text, "data" URLs are a perfect delivery mechanism. I wrote an article outlining my efforts at sparkline embedding and included sample PHP code for implementing data URLs to deliver Google Chart API-generated sparklines: How to embed sparklines inline into web pages with "data" URLs (and a little PHP) -- Jim Dahl (email) I've been working on a light weight performance monitoring solution which can be hosted on a LAMP (or WAMP, or OSX =) installation and uses the Google chart API to present data in a sparkline format. I'm using shaded bands (with borders determined by 20-80th percentiles) to help users quickly detect anomalies. There is a blog about this approach here You're welcome to view a demonstration at NumbrCrunchr.com or contribute to the open source project http://code.google.com/p/numbrcrunchr/ Look forward to people's thoughts on this approach. -- Tim Koopmans (email) The jQuery Sparkline plugin also uses data URIs to generate its charts. This is a simple and easy way to be able to generate them on the browser side without having to send your data off to a remote API or rely on image downloads. A project I recently worked on used this plugin to generate a data grid that contained sparklines for viewing web traffic trends. The project is open source and the license and instructions to download are inside the index.html HTML source. -- Daniel Einspanjer (email) I just saw a video that promises native sparklines inside Microsoft Excel 2010. See the YouTube video here: https://www.youtube.com/watch?v=Iu764Eef8TE -- Michael Kane (email) Edward: In early 1998, Mike Medved was struggling for a way to represent graphs economically in E*Trade QuoteTracker (originally Medved QuoteTracker, by 2GK). Thinking it should have been obvious, I described the following, and he had it coded in Delphi in about 30 minutes: Unfortunately, in the intervening 11 years he has removed some even better concepts that may now be vulnerable to patenting! --Peter Zelchenko | http://pete.zelchenko.com/P -- Peter Zelchenko (email) Will Larson wrote sparklines.js, a handy bit of Javascript for generating sparklines in Javascript using Processing.js. You can see live examples at the linked page. Sparklines.js does not require any special browser plugins (though it does require a browser that supports the HTML5 canvas element—currently, FireFox, Safari, Opera and Chrome). I made a slight modification to Will's work, adding support for highlighting max values in bar charts. My version is available here at GitHub. -- J.D. Hollis (email) Mike Kidner has provided a nice matlab implementation of sparklines. Here's the link to the matlab implementation http://www.mathworks.com/matlabcentral/fileexchange/26408-sparklines-mrfk Shame that Micro$oft have disappointed us once again and pursued patenting an idea they clearly didn't think of first.

Stu in Sydney

-- Stuart Smith, Sydney Australia (email)

Examples of (animated) sparklinesimplemented using the wonderful D3.js library.

You'll need a "modern" HTML5-compliant browser to enjoy this.

-- Chris Pudney (email)

 Threads relevant to sparklines: Formula 1 real-time telemetry displaysNarrative sparklines should replace one-at-time instantaneous performance readings.Sparkline > Steve Jobs > Andy Warhol in Google resultsSparkline theory and practice Edward TufteA sparkline is a small intense, simple, word-sized graphic with typographic resolution. Sparklines mean that graphics are no longer cartoonish special occasions with captions and boxes, but rather sparkline graphic can be everywhere a word or number can be: embedded in a sentence, table, headline, map, spreadsheet, graphic. From Edward Tufte's book Beautiful Evidence. Sports graphicsSports data (along with financial and medical data) are an obvious and natural application of sparklines.Validation of Sparkline Computer Code An early effort to set sparkline code standards, an effort which was soon overwhelmed by all the different codings.Wavefields: intense animated data graphics