├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── man └── sparkline.1 ├── pyproject.toml ├── setup.cfg ├── setup.py ├── sparkline ├── __init__.py ├── __main__.py └── sparkline.py └── tests ├── test_guess.py ├── test_main.py └── test_sparkline.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | *.egg 3 | *.egg-info 4 | dist 5 | build 6 | .coverage 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021, Brandon Whaley , et al. 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 9 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | include LICENSE 3 | recursive-include sparkline *.py 4 | recursive-include man * 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | pysparkline 2 | ==== 3 | 4 | Python 3 clone of [Zach Holman's BASH sparkline project](https://github.com/holman/spark) 5 | 6 | Takes series data via stdin, command line, or API and prints a sparkline representation. 7 | 8 | Usage: 9 | 10 | - $ `sparkline 4 3 2 1` 11 | ``` 12 | █▆▃▁ 13 | ``` 14 | - $ `echo "1.0 1.0 2.0 3.0 5.0 8.0 13.0" | sparkline` 15 | ``` 16 | ▁▁▂▂▃▅█ 17 | ``` 18 | - $ `seq 20 | sort -R | sparkline -r2` 19 | ``` 20 | ▃▁ █▂ ▂▆▅ ▄▇▆ 21 | ██▃██▅▇▄▁███▃▇███▂█▆ 22 | ``` 23 | - $ `python3 -c "import sparkline; print(sparkline.sparkify([1.0, 2.0, 3.0, 4.0]))"` 24 | ``` 25 | ▁▃▆█ 26 | ``` 27 | - $ `python3 -c "import math, sparkline; print(sparkline.sparkify([math.cos(n/10.0) for n in range(-50, 50, 2)], rows=4))"` 28 | ``` 29 | ▁▃▅▇███▇▅▃▁ 30 | ▅▂ ▃▆███████████▆▃ ▂ 31 | ██▇▄▁ ▂▅█████████████████▅▂ ▁▄▇█ 32 | █████▆▄▃▁▁▁▂▃▅▇█████████████████████▇▅▃▂▁▁▁▃▄▆████ 33 | ``` 34 | -------------------------------------------------------------------------------- /man/sparkline.1: -------------------------------------------------------------------------------- 1 | .\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.1. 2 | .TH SPARKLINE "1" "December 2021" "sparkline 1.4" "User Commands" 3 | .SH NAME 4 | sparkline \- manual page for sparkline 1.4 5 | .SH DESCRIPTION 6 | usage: sparkline [\-h] [\-\-version] [\-\-min MIN] [\-\-max MAX] [\-\-rows ROWS] 7 | .IP 8 | [data ...] 9 | .PP 10 | Reads from command line args or stdin and prints a sparkline from the data. 11 | Requires at least 2 data points as input. 12 | .SS "positional arguments:" 13 | .TP 14 | data 15 | Floating point data, any delimiter. 16 | .SS "optional arguments:" 17 | .TP 18 | \fB\-h\fR, \fB\-\-help\fR 19 | show this help message and exit 20 | .TP 21 | \fB\-\-version\fR, \fB\-v\fR 22 | Display the version number and exit. 23 | .TP 24 | \fB\-\-min\fR MIN 25 | Set smaller values to MIN. 26 | .TP 27 | \fB\-\-max\fR MAX 28 | Set larger values to MAX. 29 | .TP 30 | \fB\-\-rows\fR ROWS, \fB\-r\fR ROWS 31 | Number of rows high the graph will be. 32 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools >= 51.0.0", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = pysparklines 3 | version = 1.4 4 | description = pysparklines is a unicode sparkline generation library. 5 | long_description = file: README.md 6 | long_description_content_type = text/markdown; charset=UTF-8 7 | author = Brandon Whaley 8 | author_email = redkrieg@gmail.com 9 | url = https://github.com/RedKrieg/pysparklines 10 | platform = any 11 | license = BSD 3-clause 12 | license_file = LICENSE 13 | classifiers = 14 | Development Status :: 5 - Production/Stable 15 | Environment :: Console 16 | Intended Audience :: Developers 17 | Intended Audience :: System Administrators 18 | License :: OSI Approved :: BSD License 19 | Operating System :: Unix 20 | Operating System :: POSIX 21 | Programming Language :: Python 22 | Programming Language :: Python :: 3 :: Only 23 | Topic :: Software Development 24 | Topic :: Software Development :: Libraries 25 | Topic :: Software Development :: Libraries :: Python Modules 26 | 27 | [options] 28 | packages = find: 29 | python_requires = >=3.2 30 | 31 | [bdist_wheel] 32 | universal = 1 33 | 34 | [options.entry_points] 35 | console_scripts = 36 | sparkline = sparkline:main 37 | 38 | [options.extras_require] 39 | test = pytest; pytest-cov 40 | 41 | [coverage:run] 42 | branch = True 43 | 44 | [coverage:report] 45 | show_missing = True 46 | 47 | [tool:pytest] 48 | addopts = --cov sparkline --cov-branch --cov-report term-missing 49 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import setuptools 4 | 5 | if __name__ == "__main__": 6 | setuptools.setup() 7 | -------------------------------------------------------------------------------- /sparkline/__init__.py: -------------------------------------------------------------------------------- 1 | from .sparkline import * 2 | -------------------------------------------------------------------------------- /sparkline/__main__.py: -------------------------------------------------------------------------------- 1 | from .sparkline import main # pragma: no cover 2 | 3 | if __name__ == "__main__": # pragma: no cover 4 | main() 5 | -------------------------------------------------------------------------------- /sparkline/sparkline.py: -------------------------------------------------------------------------------- 1 | # vim: set fileencoding=utf-8 : 2 | import math, os, re, string, sys 3 | 4 | __all__ = ["guess_series", "main", "spark_chars", "sparkify"] 5 | 6 | spark_chars = u"▁▂▃▄▅▆▇█" 7 | """Eight unicode characters of (nearly) steadily increasing height.""" 8 | 9 | 10 | def sparkify(series, minimum=None, maximum=None, rows=1): 11 | u"""Converts to a sparkline string. 12 | 13 | Example: 14 | >>> sparkify([ 0.5, 1.2, 3.5, 7.3, 8.0, 12.5, float("nan"), 15.0, 14.2, 11.8, 6.1, 15 | ... 1.9 ]) 16 | u'▁▁▂▄▅▇ ██▆▄▂' 17 | 18 | >>> sparkify([1, 1, -2, 3, -5, 8, -13]) 19 | u'▆▆▅▆▄█▁' 20 | 21 | Raises ValueError if input data cannot be converted to float. 22 | Raises TypeError if series is not an iterable. 23 | """ 24 | series = [float(n) for n in series] 25 | if all(not math.isfinite(n) for n in series): 26 | return u" " * len(series) 27 | 28 | minimum = min(filter(math.isfinite, series)) if minimum is None else minimum 29 | maximum = max(filter(math.isfinite, series)) if maximum is None else maximum 30 | data_range = maximum - minimum 31 | if data_range == 0.0: 32 | # Graph a baseline if every input value is equal. 33 | return u"".join([spark_chars[0] if math.isfinite(i) else u" " for i in series]) 34 | row_res = len(spark_chars) 35 | resolution = row_res * rows 36 | coefficient = (resolution - 1.0) / data_range 37 | 38 | def clamp(n): 39 | return min(max(n, minimum), maximum) 40 | 41 | def spark_index(n): 42 | """An integer from 0 to (resolution-1) proportional to the data range""" 43 | return int(round((clamp(n) - minimum) * coefficient)) 44 | 45 | output = [] 46 | for r in range(rows - 1, -1, -1): 47 | row_out = [] 48 | row_min = row_res * r 49 | row_max = row_min + row_res - 1 50 | for n in series: 51 | if not math.isfinite(n): 52 | row_out.append(" ") 53 | continue 54 | i = spark_index(n) 55 | if i < row_min: 56 | row_out.append(" ") 57 | elif i > row_max: 58 | row_out.append(spark_chars[-1]) 59 | else: 60 | row_out.append(spark_chars[i % row_res]) 61 | output.append(u"".join(row_out)) 62 | return os.linesep.join(output) 63 | 64 | 65 | def _convert_to_float(n): 66 | try: 67 | return float(n) 68 | except ValueError: 69 | return None 70 | 71 | 72 | def guess_series(input_string): 73 | u"""Tries to convert into a list of floats. 74 | 75 | Example: 76 | >>> guess_series("0.5 1.2 3.5 7.3 8 nan 12.5, 13.2," 77 | ... "15.0, 14.2, 11.8, 6.1, 1.9") 78 | [0.5, 1.2, 3.5, 7.3, 8.0, nan, 12.5, 13.2, 15.0, 14.2, 11.8, 6.1, 1.9] 79 | """ 80 | float_finder = re.compile( 81 | r"(nan|[-+]?inf|[-+]?[0-9]*\.?[0-9]+(?:e[-+]?[0-9]+)?)", re.I 82 | ) 83 | return [ 84 | i 85 | for i in [ 86 | _convert_to_float(j) 87 | for j in float_finder.findall(input_string) 88 | # Remove entires we couldn't convert to a sensible value. 89 | ] 90 | if i is not None 91 | ] 92 | 93 | 94 | def main(argv=None): 95 | u"""Reads from command line args or stdin and prints a sparkline from the 96 | data. Requires at least 2 data points as input. 97 | """ 98 | import argparse 99 | from pkg_resources import require 100 | 101 | if not argv: # pragma: no cover 102 | argv = sys.argv[1:] 103 | parser = argparse.ArgumentParser(description=main.__doc__) 104 | parser.add_argument("data", nargs="*", help="Floating point data, any delimiter.") 105 | parser.add_argument( 106 | "--version", 107 | "-v", 108 | action="store_true", 109 | help="Display the version number and exit.", 110 | ) 111 | parser.add_argument("--min", type=float, help="Set smaller values to MIN.") 112 | parser.add_argument("--max", type=float, help="Set larger values to MAX.") 113 | parser.add_argument( 114 | "--rows", 115 | "-r", 116 | type=int, 117 | default=1, 118 | help="Number of rows high the graph will be.", 119 | ) 120 | args = parser.parse_args(argv) 121 | 122 | if args.version: # pragma: no cover 123 | version = require("pysparklines")[0].version 124 | print(version) 125 | sys.exit(0) 126 | 127 | if os.isatty(0) and not args.data: # pragma: no cover 128 | parser.print_help() 129 | sys.exit(1) 130 | elif args.data: 131 | arg_string = u" ".join(args.data) 132 | else: # pragma: no cover 133 | arg_string = sys.stdin.read() 134 | 135 | try: 136 | print( 137 | sparkify( 138 | guess_series(arg_string), 139 | minimum=args.min, 140 | maximum=args.max, 141 | rows=args.rows, 142 | ) 143 | ) 144 | except Exception: # pragma: no cover 145 | sys.stderr.write("Could not convert input data to valid sparkline" + os.linesep) 146 | sys.exit(1) 147 | 148 | 149 | if __name__ == "__main__": # pragma: no cover 150 | main() 151 | -------------------------------------------------------------------------------- /tests/test_guess.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import sparkline 3 | 4 | 5 | def test_convert(): 6 | assert sparkline.sparkline._convert_to_float("1.0") == 1.0 7 | assert sparkline.sparkline._convert_to_float("Garbage") == None 8 | 9 | 10 | def test_int(): 11 | assert sparkline.guess_series("Garbage 1 2 3") == [1.0, 2.0, 3.0] 12 | 13 | 14 | def test_exponent(): 15 | assert sparkline.guess_series("-1.1e-4 5.5 2.1e2") == [-0.00011, 5.5, 210.0] 16 | 17 | 18 | def test_inf(): 19 | assert sparkline.guess_series("-inf +inf 1 2") == [ 20 | float("-inf"), 21 | float("inf"), 22 | 1.0, 23 | 2.0, 24 | ] 25 | -------------------------------------------------------------------------------- /tests/test_main.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import runpy 3 | import sparkline 4 | 5 | 6 | def test_min_max(capsys): 7 | sparkline.main("--min 2 --max 7 0 1 2 3 4 5 6 7 8 9 10".split()) 8 | captured = capsys.readouterr() 9 | assert captured.out == u"▁▁▁▂▄▅▇████\n" 10 | 11 | 12 | def test_rows(capsys): 13 | sparkline.main("--rows 3 0 1 2 3 4 5 6 7 8 9 10".split()) 14 | captured = capsys.readouterr() 15 | assert ( 16 | captured.out 17 | == u""" ▁▃▆█ 18 | ▂▅▇████ 19 | ▁▃▆████████ 20 | """ 21 | ) 22 | -------------------------------------------------------------------------------- /tests/test_sparkline.py: -------------------------------------------------------------------------------- 1 | # vim: set fileencoding=utf-8 : 2 | import pytest 3 | import sparkline 4 | 5 | 6 | def test_1234(): 7 | assert sparkline.sparkify([1, 2, 3, 4]) == u"▁▃▆█" 8 | 9 | 10 | def test_range_8(): 11 | assert sparkline.sparkify(range(8)) == u"▁▂▃▄▅▆▇█" 12 | 13 | 14 | def test_range_9(): 15 | assert sparkline.sparkify(range(9)) == u"▁▂▃▄▅▅▆▇█" 16 | 17 | 18 | def test_inf(): 19 | assert sparkline.sparkify([float("-inf"), 0, float("inf")]) == u" ▁ " 20 | 21 | 22 | def test_nan(): 23 | assert sparkline.sparkify([float("nan"), 0, 1]) == u" ▁█" 24 | 25 | 26 | def test_all_nan_or_inf(): 27 | assert sparkline.sparkify([float("nan"), float("-inf")]) == u" " 28 | 29 | 30 | def test_min(): 31 | assert sparkline.sparkify([1, 2, 3, 4], minimum=2) == u"▁▁▅█" 32 | 33 | 34 | def test_max(): 35 | assert sparkline.sparkify([1, 2, 3, 4], maximum=3) == u"▁▅██" 36 | 37 | 38 | def test_min_max(): 39 | assert sparkline.sparkify([1, 2, 3, 4], minimum=2, maximum=3) == u"▁▁██" 40 | 41 | 42 | def test_fib(): 43 | assert sparkline.sparkify([1.0, 1.0, 2.0, 3.0, 5.0, 8.0, 13.0]) == u"▁▁▂▂▃▅█" 44 | 45 | 46 | def test_multiline(): 47 | import math 48 | 49 | assert ( 50 | sparkline.sparkify([math.cos(n / 10.0) for n in range(-50, 50, 2)], rows=4) 51 | == u""" ▁▃▅▇███▇▅▃▁ 52 | ▅▂ ▃▆███████████▆▃ ▂ 53 | ██▇▄▁ ▂▅█████████████████▅▂ ▁▄▇█ 54 | █████▆▄▃▁▁▁▂▃▅▇█████████████████████▇▅▃▂▁▁▁▃▄▆████""" 55 | ) 56 | --------------------------------------------------------------------------------