Skip to content

Commit 2aa0ba7

Browse files
author
Nick Tomasino
committed
Adding a horizontal bar chart (hbar)
1 parent 4a4c30f commit 2aa0ba7

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

plotille/_graphs.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,59 @@
2525

2626
from math import log
2727
import os
28+
from typing import List, Optional
2829

2930
from ._colors import color
3031
from ._figure import Figure
3132
from ._input_formatter import InputFormatter
3233
from ._util import hist as compute_hist
3334

3435

36+
def hbar(counts, labels=Optional[List[str]], width=80, log_scale=False, linesep=os.linesep,
37+
lc=None, bg=None, color_mode='names'):
38+
"""
39+
Create histogram for aggregated data.
40+
41+
Parameters:
42+
counts: List[int] Counts for each bucket.
43+
labels: List[str] Labels for the provided counts. Optional.
44+
Hence, `len(labels) == len(counts)`.
45+
width: int The number of characters for the width (columns).
46+
log_scale: bool Scale the histogram with `log` function.
47+
linesep: str The requested line seperator. default: os.linesep
48+
lc: multiple Give the line color.
49+
bg: multiple Give the background color.
50+
color_mode: str Specify color input mode; 'names' (default), 'byte' or 'rgb'
51+
see plotille.color.__docs__
52+
Returns:
53+
str: histogram over `X` from left to right.
54+
"""
55+
def _scale(a):
56+
if log_scale and a > 0:
57+
return log(a)
58+
return a
59+
60+
h = counts
61+
62+
ipf = InputFormatter()
63+
l_max = max(len(label) for label in labels)
64+
h_max = _scale(max(h)) or 1
65+
66+
bins_count = len(h)
67+
68+
canvas = ['{}| {} {}'.format('label'.ljust(l_max + 1), '_' * width, 'Total Counts')]
69+
lasts = ['', '⠂', '⠆', '⠇', '⡇', '⡗', '⡷', '⡿']
70+
for i in range(bins_count):
71+
height = int(width * 8 * _scale(h[i]) / h_max)
72+
canvas += ['{} | {} {}'.format(
73+
ipf.fmt(labels[i], delta=None, chars=l_max, left=True),
74+
color('⣿' * (height // 8) + lasts[height % 8], fg=lc, bg=bg, mode=color_mode)
75+
+ color('\u2800' * (width - (height // 8) + int(height % 8 == 0)), bg=bg, mode=color_mode),
76+
h[i])]
77+
canvas += ['‾' * (l_max + 2 + 3 + width + 12)]
78+
return linesep.join(canvas)
79+
80+
3581
def hist_aggregated(counts, bins, width=80, log_scale=False, linesep=os.linesep,
3682
lc=None, bg=None, color_mode='names'):
3783
"""

0 commit comments

Comments
 (0)