Data Visualization: Draw a box plot as text

Draw the whole box plot, outliers included, on one line of text.

What to build

A program that draws a horizontal box plot W characters wide.

Requirements

  • Compute Q1, the median and Q3 by linear interpolation, the fences at 1.5 IQR, the whisker ends (the most extreme values inside the fences) and the outliers.
  • Start with W spaces and draw, each layer overwriting the last: - from the low whisker to Q1 and from Q3 to the high whisker (inclusive); = from Q1 to Q3; [ at Q1 and ] at Q3; + at both whisker ends; | at the median; o at each outlier.
  • Print the line, then min M, Q1 A, median B, Q3 C, max D, every number written with :g.

Input

Line 1: W. Line 2: the values separated by spaces.

Output

Two lines.

Constraints

5 ≤ W ≤ 80; 1 to 1000 values.

Example

Input:

21
1 2 3 4 5 6 7 8

Output:

+----[====|====]----+
min 1, Q1 2.75, median 4.5, Q3 6.25, max 8

Why it works

Drawing in a fixed order of layers decides what wins when two parts land on the same column, so the median and outliers always stay visible, as in a real box plot.

Examples

Example 1 · Input
21
1 2 3 4 5 6 7 8
Expected output
+----[====|====]----+
min 1, Q1 2.75, median 4.5, Q3 6.25, max 8
Example 2 · Input
11
31 52 61 64 67 70 71 73 75 78 80 84 97
Expected output
o  +-[|]--+
min 31, Q1 64, median 71, Q3 78, max 97

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Draw in layers on a list of W spaces: whisker lines, then the box, then its edges, the whisker ends, the median and the outliers.

Hint 2

Positions use the smallest and largest of all values: int((v − min) / (max − min) × (W − 1) + 0.5), or 0 when they are equal.

Solution

Show one correct solution (try it yourself first)
w = int(input())
values = sorted(float(v) for v in input().split())
n = len(values)


def quantile(p):
    pos = (n - 1) * p
    i = int(pos)
    if i + 1 >= n:
        return values[i]
    return values[i] + (pos - i) * (values[i + 1] - values[i])


q1, med, q3 = quantile(0.25), quantile(0.5), quantile(0.75)
iqr = q3 - q1
inside = [v for v in values if q1 - 1.5 * iqr <= v <= q3 + 1.5 * iqr]
outliers = [v for v in values if v not in inside]
lo, hi = values[0], values[-1]


def pos(v):
    return 0 if hi == lo else int((v - lo) / (hi - lo) * (w - 1) + 0.5)


line = [" "] * w
for a, b in ((inside[0], q1), (q3, inside[-1])):
    for i in range(pos(a), pos(b) + 1):
        line[i] = "-"
for i in range(pos(q1), pos(q3) + 1):
    line[i] = "="
line[pos(q1)] = "["
line[pos(q3)] = "]"
line[pos(inside[0])] = "+"
line[pos(inside[-1])] = "+"
line[pos(med)] = "|"
for v in outliers:
    line[pos(v)] = "o"
print("".join(line))
print(f"min {lo:g}, Q1 {q1:g}, median {med:g}, Q3 {q3:g}, max {hi:g}")

Lesson: Box plots and quartiles →