[Tutor] Stem and leaf plots

Steven D'Aprano steve at pearwood.info
Mon May 18 16:32:38 CEST 2015


On Sun, May 17, 2015 at 02:50:39PM -0700, Danny Yoo wrote:
> I was reading the "Cartoon Guide to Statistics", and came across a
> description on "Stem and plot diagrams".
> (http://en.wikipedia.org/wiki/Stem-and-leaf_display.)  It's sorta like
> a histogram diagram, but bundles by the ten's digit, and uses the
> one's digit as the "point".
> 
> Here's my attempt at describing it as a program:
> 
> ###########################################################
> """
> Stem and leaf plotting.
> http://en.wikipedia.org/wiki/Stem-and-leaf_display.
> """
> 
> import collections
> import sys
> 
> 
> def printStemPlot(values):
>     """Prints a stem plot of the values."""
>     stems = collections.defaultdict(list)
>     for v in values:
>         stems[v / 10].append(v % 10)
> 
>     low, high = min(stems.keys()), max(stems.keys())
>     padding = len(str(high))
>     for i in range(low, high+1):
>         stems[i].sort()
>         print(str(i).ljust(padding) + ' | ' +
>               ' '.join(map(str, stems[i])))def printStemPlot(values):

Nice!

It doesn't cope with Stem-and-leaf plots in their full generality, e.g.: 
stem-widths which are not 10:

4 | 1 2 2 4
  | 5 7 9 9 9
5 | 0 0 3
  | 5 8


and you should print the stem and leaf width and give a key, but it's 
otherwise excellent. Thank you for sharing!
 

-- 
Steve


More information about the Tutor mailing list