[Tutor] Stem and leaf plots

Danny Yoo dyoo at hashcollision.org
Sun May 17 23:50:39 CEST 2015


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):

if __name__ == "__main__":
    printStemPlot([int(n) for n in sys.argv[1:]])
###########################################################


For example:

###########################################################
$ python stemplot.py 44 46 47 49 63 64 66 68 68 72 72 75 76 81 84 88 106
4  | 4 6 7 9
5  |
6  | 3 4 6 8 8
7  | 2 2 5 6
8  | 1 4 8
9  |
10 | 6
###########################################################


The program came out really short and sweet, especially with the use
of collections.defaultdict, so I'm happy with it.


Hope everyone's having a good weekend!


More information about the Tutor mailing list