a python command-line tool which draws basic graphs in the terminal

Overview

Termgraph

A command-line tool that draws basic graphs in the terminal, written in Python.

Graph types supported:

  • Bar Graphs
  • Color charts
  • Multi-variable
  • Stacked charts
  • Histograms
  • Horizontal or Vertical
  • Emoji!

Examples

termgraph data/ex1.dat

# Reading data from data/ex1.dat

2007: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 183.32
2008: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 231.23
2009: ▇ 16.43
2010: ▇▇▇▇ 50.21
2011: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 508.97
2012: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 212.05
2014: ▏ 1.00

An example using emoji as custom tick:

termgraph data/ex1.dat --custom-tick "🏃" --width 20 --title "Running Data"

# Running Data

2007: 🏃🏃🏃🏃🏃🏃🏃 183.32
2008: 🏃🏃🏃🏃🏃🏃🏃🏃🏃 231.23
2009:  16.43
2010: 🏃 50.21
2011: 🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃🏃 508.97
2012: 🏃🏃🏃🏃🏃🏃🏃🏃 212.05
2014:  1.00

An example using stdin and emoji:

echo "Label,3,9,1" | termgraph --custom-tick "😀" --no-label


😀😀😀 3.00
😀😀😀😀😀😀😀😀😀 9.00
😀 1.00

Most results can be copied and pasted wherever you like, since they use standard block characters. However the color charts will not show, since they use terminal escape codes for color. A couple images to show color examples:

termgraph data/ex4.dat --color {blue,red}

Multi variable bar chart with colors

termgraph data/ex7.dat --color {yellow,magenta} --stacked --title "Stacked Data"

Multi variable stacked bar chart with colors

Calendar Heatmap, expects first column to be date in yyyy-mm-dd

termgraph --calendar --start-dt 2017-07-01 data/cal.dat

Calendar Heatmap

Install

Requires Python 3.5+, install from PyPI project

python -m pip install termgraph

Note: Be sure your PATH includes the pypi install directory, for me it is ~/.local/bin/

Usage

  • Create data file with two columns either comma or space separated. The first column is your labels, the second column is a numeric data

  • termgraph [datafile]

  • Help: termgraph -h

usage: termgraph.py [-h] [--title TITLE] [--width WIDTH] [--format FORMAT]
  [--suffix SUFFIX]
  [--label-before] [--no-labels] [--no-values]
  [--color [{red,blue,green,magenta,yellow,black,cyan} [{...} ...]]]
  [--vertical] [--stacked] [--different-scale] [--calendar]
  [--start-dt START_DT] [--custom-tick CUSTOM_TICK] [--delim DELIM]
  [--verbose] [--version]
  [filename]

draw basic graphs on terminal

positional arguments:
  filename              data file name (comma or space separated). Defaults to stdin.

optional arguments:
  -h, --help            show this help message and exit
  --title TITLE         Title of graph
  --width WIDTH         width of graph in characters default:50
  --format FORMAT       format specifier to use.
  --suffix SUFFIX       string to add as a suffix to all data points.
  --no-labels           Do not print the label column
  --no-values           Do not print the values at end
  --color [{red,blue,green,magenta,yellow,black,cyan} [{...} ...]]
                        Graph bar color( s )
  --vertical            Vertical graph
  --stacked             Stacked bar graph
  --different-scale     Categories have different scales.
  --calendar            Calendar Heatmap chart
  --start-dt START_DT   Start date for Calendar chart
  --custom-tick CUSTOM_TICK
                        Custom tick mark, emoji approved
  --delim DELIM         Custom delimiter, default , or space
  --verbose             Verbose output, helpful for debugging
  --label-before        Display the values before the bars
  --version             Display version and exit

Background

I wanted a quick way to visualize data stored in a simple text file. I initially created some scripts in R that generated graphs but this was a two step process of creating the graph and then opening the generated graph.

After seeing command-line sparklines I figured I could do the same thing using block characters for bar charts.

Contribute

All contributions are welcome, for feature requests or bug reports, use Github Issues. Pull requests are welcome to help fix or add features.

Code contributions: This repository uses the black code formatter to automatically format the code. A Github Action is setup to lint your code, to avoid failures it is recommended to setup your editor to auto format on save.

Thanks to all the contributors!

License

MIT License, see LICENSE.txt

Comments
  • prepare script for submission to PyPi

    prepare script for submission to PyPi

    Overview of Changes

    Files added:

    • setup.py - instructs python how to install the script as a package
    • LICENSE.txt - includes contents of MIT license
      • replace the contents with whatever license you want
    • manifest.in - instructs python to include the license file in the package
    • termigraph/init.py - necessary for building package

    File changed:

    • moved termgraph.py to termgraph/termgraph.py - necessary for building package
    • in termgraph.py - adjusted main() so it is directly callable

    preperation

    Review setup.py and change and adjust any value you wish, particularly:

    • version
    • your name
    • possibly add an author_email field
    • license
    • description
    • keywords

    Review LICENSE.txt

    • Make sure its the license type you want
    • change your name after the copyright statement in line 3

    create distribution files

    • create an account on PyPi
    • update setuptools, wheel and twine
      • pip3 install -U setuptools (and so likewise for wheel & twine)
    • build the source distribution: python3 setup.py sdist
    • build the wheel for python 3: python3 setup.py bdist_wheel

    local test before submission

    You now have build files, but before submitting them, you can perform a local test install

    • cd into the "dist" folder and run: pip install termgraph-0.1.0-py3-none-any.whl
    • this will install termgraph on your computer using the wheel generated by setup.py and link it to your path.
      • run this version by typing "termgraph" (no .py needed)
    • Once you've verified that it works, you can uninstall it by typing "pip3 uninstall termgraph"

    submitting to PyPi

    Once you're ready to submit it to PyPi, and you've changed the values in setup.py

    • build the source distribution: python3 setup.py sdist
    • build the wheel for python 3: python3 setup.py bdist_wheel
    • the first time you submit it to PyPi
      • register the source code: twine register dist/termgraph-0.1.0.tar.gz (Substitute your version #)
      • register the wheel: twine register dist/termgraph-0.1.0-py3-none-any.whl
    • Upload the files to PyPi: twine upload dist/*

    Installing on local machine in developer mode

    Whenever you want to edit the script and see local changes immediately (without reinstalling each time), you can install the package in developer mode.

    • First, make sure the package isn't already installed with pip
      • run pip3 uninstall termgraph
    • cd into the directory containing setup.py
    • type pip3 install -e .

    Publishing new Releases to PyPi

    • change the version # in setup.py
    • run the commands to generated updated distribution & wheel files
      • the version number in the files will change
    • upload the new versions
      • make sure to delete the old tar & wheel files from the "dist" directory
    opened by robertpeteuil 9
  • Interest in a PR to enable submission to PyPi?

    Interest in a PR to enable submission to PyPi?

    This is very cool, and it can me made even more useful by adding it to PyPi.

    This would allow people to easily install it with pip, instead of requiring manual steps to: install pre-requisites, download the script and copy it to a location on the path.

    I can submit a PR that prepares the repo for PyPi:

    • adjust the script to run as a module
    • create setup.py
    • ~convert readme.md to readme.rst~
      • ~PyPi uses restructured text to create module documentation (not markdown)~ no longer required per @jChapman's comment below

    After merging the PR, all you would need to do is:

    • add a license
    • create an account on PyPi
    • create & upload distribution files to PyPi

    Let me know if you're interested in this. As an example, here's one of my repos that's registered in PyPi

    opened by robertpeteuil 7
  • Treat zero data points the same as missing data points.

    Treat zero data points the same as missing data points.

    Sometimes the data set contains zero-valued data points. Since they are exactly zero, they should IMO be treated the same as when a data point is missing. However, they are currently displayed as non-zero values from the bottom quartile.

    This PR changes this behaviour to treat them the same as missing data points (printing a space).

    opened by dkasak 5
  • Compatibility issues with Python versions <= 3.6

    Compatibility issues with Python versions <= 3.6

    I cant initialize the termgraph command. Neither for 2.7 or 3.5:

    I installed via pip and pip3

    python 2.7:

    [email protected]:pts/0->/home/odit (0) 
    > termgraph
    Traceback (most recent call last):
      File "/home/linuxbrew/.linuxbrew/bin/termgraph", line 7, in <module>
        from termgraph.termgraph import main
      File "/home/linuxbrew/.linuxbrew/Cellar/[email protected]/2.7.14_4/lib/python2.7/site-packages/termgraph/termgraph.py", line 172
        sys.stdout.write( f'\033[{color}m' ) # Start to write colorized.
                                         ^
    SyntaxError: invalid syntax
    
    

    Python3.5:

    Traceback (most recent call last):
      File "/home/odit/.local/bin/termgraph", line 7, in <module>
        from termgraph.termgraph import main
      File "/home/odit/.local/lib/python3.5/site-packages/termgraph/termgraph.py", line 172
        sys.stdout.write( f'\033[{color}m' ) # Start to write colorized.
                                         ^
    SyntaxError: invalid syntax
    
    opened by xrefor 5
  • Object-oriented / code restructure

    Object-oriented / code restructure

    At the moment, termgraph uses many functions inside one script to achieve its goal. It works well, but it might be better to use classes and a more object-oriented approach. This would make it more organized, easier to build upon and easier to re-use in other projects.

    The problem is that it will change a lot of the existing code structure, meaning it will break other projects which use termgraph unless they adopt these changes.

    The upside is that it will make future development easier, and it will be easier for others to use this library in their own project. For example, it would make #27 easy to fix.

    However, I understand if this project has progressed too far for this to be done, and restructuring all the code might not be worth the effort. But I am willing to do this myself, I have enough time available and this would be a good learning opportunity.

    opened by nnist 4
  • SyntaxError

    SyntaxError

    some error

      File "termgraph.py", line 163
        sys.stdout.write( f'\033[{color}m' ) # Start to write colorized.
                                         ^
    SyntaxError: invalid syntax
    
    

    i fix it by remove all "f"

    sys.stdout.write( '\033[{color}m' )

    opened by MGF15 4
  • Cannot import API module

    Cannot import API module

    The new API module as defined in #27 and #75 cannot be imported:

    >>> from termgraph.module import Data, BarChart, Args, Colors
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/user/.local/share/virtualenvs/foo-IGGZy7fP/lib/python3.9/site-packages/termgraph/module.py", line 12, in <module>
        from utils import cvt_to_readable
    ModuleNotFoundError: No module named 'utils'
    
    opened by yuvadm 3
  • Made Termgraph an API/Module and some new features

    Made Termgraph an API/Module and some new features

    I have made termgraph an API/module to use in other scripts and would like it to be merged with the base repository.

    I have kept the structure very simple and anyone can easily extend upon it and add other types of charts to the module. Some other features have also been added.

    I have made some changes in termgraph.py itself and the API/module code can be found in module.py (I know I am really bad at naming things)

    Issues Handled: #27, #39, #47

    Features Added:

    • New param space-between that lets you print an extra space between two rows so that it looks cleaner
    • Human Readable Format for values as requested (https://github.com/mkaz/termgraph/issues/43#issuecomment-580855325)

    image

    API/Module:

    Colors

    It houses all the colours that can be used in termgraph

    Args

    The Args class is basically the same thing as passing args through the command line. You can pass args as keyword arguments or use update_args on an Args instance. Args are directly passed into Chart.

    Data

    The Data class merges the data, labels and categories all in one. I wasn't able to add normal_data to it as well cause the normalize function required 'width' parameter for which we needed the access to the args but they are only accessible by Chart. So the only resolution was passing the args to data as well which didn't seem like a good idea. So took the normalize function and put it in Chart class. You can also visualize the data by just printing it or by using the str() function on it. It also has a property called dims (I was inspired by NumPy for this) which may or may not be helpful but I added it for future use.

    Chart

    The Chart class takes in the data and the args. It is drawn by using the draw() method. It is an abstract-ish class and has nothing special in it except for the _normalize() method which is the same as before and _print_header() method which prints the title and category names.

    Horizontal Chart

    It is derived off of the Chart class and the main reason for deriving the new chart off of this is that it contains the print_row function. I did so because no other chart required access to the function except for the ones which are horizontal.

    I was only able to implement Bar Chart due to time limitations and my exams approaching and some other reasons. Below is the example code for usage (it can also be found in example.py)

    from module import Data, BarChart, Args, Colors
    
    data = Data(data=[[765, 787], [781, 769]], labels=["6th G", "7th G"], categories=["Boys", "Girls"])
    chart = BarChart(data, Args(title="Total Marks Per Class", colors=[Colors.Red, Colors.Magenta], space_between=True))
    
    chart.draw()
    

    image

    opened by AdityaTaggar05 3
  • Bad display with --stacked

    Bad display with --stacked

    The display in column doesn't work properly with the --stacked option.

    Example1: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 22.00
    Longertext example : ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 36.00
    

    I have to use column -t -s ':' to clean it up.

    opened by justUmen 3
  • Annotations support only works in Python3.7+, not 3.5+ as specified in the docs

    Annotations support only works in Python3.7+, not 3.5+ as specified in the docs

    https://www.python.org/dev/peps/pep-0563/#enabling-the-future-behavior-in-python-3-7

    README.md states that the minimum version is Python 3.5+, but that is incorrect.

    opened by neil-greenwood 2
  • 16 out of 21 tests failed

    16 out of 21 tests failed

    I intended to submit a pull request on bug fixes, however, the existing tests are largely broken.

    I just clone the main branch of termgraph (to be exact, commit 63491d8b6a14dba8f88087dbdbaefb290e1ec246), and run pytest tests. It outputs a bunch of errors, showing test statistics at the end:

    ================ 16 failed, 21 passed in 0.63s ==================
    

    Could you please fix these tests? @mkaz

    opened by zxytim 2
  • Color formatting of

    Color formatting of "0" values spills over to the next line

    termgraph v0.5.3

    Tested on linux (and macos using gdate instead of date) with this reproduction: for X in {30..1} ; do gdate -d "-$X days" "+%F $(( $X % 10 )) " ; done | termgraph

    Screenshot 2023-01-03 at 10 51 36 AM
    opened by danielhoherd 0
  • does not work properly when opened using subprocess.call(), subprocess.run() or similar commands in python script

    does not work properly when opened using subprocess.call(), subprocess.run() or similar commands in python script

    whenever i use subprocess.call(['termgraph', 'stats.dat']) or other similar commands in a python script, i always get this error:

    Traceback (most recent call last):
      File "/home/user/.local/bin/termgraph", line 8, in <module>
        sys.exit(main())
      File "/home/user/.local/lib/python3.10/site-packages/termgraph/termgraph.py", line 133, in main
        _, labels, data, colors = read_data(args)
      File "/home/user/.local/lib/python3.10/site-packages/termgraph/termgraph.py", line 712, in read_data
        colors = check_data(labels, data, args)
      File "/home/user/.local/lib/python3.10/site-packages/termgraph/termgraph.py", line 569, in check_data
        len_categories = len(data[0])
    IndexError: list index out of range
    

    however, these commands work outside python scripts like in the python shell or just the command line. is there any way i can allow them to run in python scripts as well?

    opened by shuu-wasseo 0
  • Include darker colors for color output

    Include darker colors for color output

    I noticed that you only allow the bright colors, which are ANSI codes 90 to 96; In the AVAILABLE_COLORS enum in your main file, if additional entries were added with the codes 30 to 36, and their respective keys given something like "dark_" as a prefix, you could double the number of colors offered to users. I might try a pull request if someone else hasn't already, doesn't seem like too big a change.

    opened by cSquaerd 0
  • Fixing AttributeError: type object 'Colors' has no attribute 'black'

    Fixing AttributeError: type object 'Colors' has no attribute 'black'

    Fixing the below exception when the value 0.0 is plotted

      File "/home/cmuck/Documents/Isas-script/venv/lib/python3.8/site-packages/termgraph/module.py", line 327, in print_row
        sys.stdout.write(f"\033[{Colors.black}m")  # dark gray
    AttributeError: type object 'Colors' has no attribute 'black' 
    
    opened by cmuck 0
  • disabling

    disabling "cvt_to_readable"

    Is there any ways to disable "cvt_to_readable": Return the number in a human readable format

    It produces wrong numbers,

        args = {
            "stacked": False,
            "width": 50,
            "no_labels": False,
            "format": "{:>5.2f}",
            "suffix": " minutes",
            "vertical": False,
            "histogram": False,
            "no_values": False,
            "different_scale": False
        }
    
        chart(colors=[TERM_GRAPH_AVAILABLE_COLORS['blue']],
              data=data,
              args=args,
              labels=labels)
    

    2022-07-09_0-27-22

    where data is:

    [ [0.42475755214691163], [0.1093926469484965], [0.04674157698949178], [0.031145751476287842], ]

    opened by ManiAm 2
Releases(v0.5.3)
  • v0.5.3(Sep 4, 2021)

  • v0.5.2(Jul 26, 2021)

  • v0.5.0(Jun 20, 2021)

    • Updates and code structuring for first use of termgraph as a module, see example.py #75 Thanks @AdityaTaggar05 for the major contribution
    • New --space-between parameter to add new line between values in chart #75
    • New convert to human readable format #75
    • Fix BrokenPipeError #80 props @danielhoherd
    Source code(tar.gz)
    Source code(zip)
  • v0.4.2(Jun 19, 2020)

    • Allow normalize to work on data smaller than width, for example values from 0-1

    Note: I tried breaking up the file, into smaller pieces in v0.4.1 but resulted in a bad build. I need to figure out how to package multiple files together.

    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(Jun 19, 2020)

    • Adds histogram support (#51 props to @HiromuIshikawa)
    • Fixes vertical graphs
    • Updates vertical graphs to honor --no-values --no-label flags
    • Windows compatibility fix for color options (props to Yuki Okushi)
    Source code(tar.gz)
    Source code(zip)
  • v0.3.1(Jun 14, 2020)

  • v0.3.0(Jun 11, 2020)

    New Flag

    • Add no --no-values flag to suppress the display of ending values

    Code Quality

    • Codestyle fixes in #64 props to @dmitriy-0297
    • Add exception check for rading file #63 props to @dmitriy-0297
    Source code(tar.gz)
    Source code(zip)
  • v0.2.3(May 19, 2020)

    Release Notes

    • Fix incompatibility bug with label_before args undefined (#57)
    • Fix min/max with multiple categories props to @MaximeVdB (#56)
    Source code(tar.gz)
    Source code(zip)
  • v0.2.2(May 13, 2020)

    Adds a new flag --label-before that displays the labels in front of the lines, not the end. Props to @wgxo for the contribution.

    Note: When using the --label-before flag, you may also want to use --format={:7.2f} or something similar so the labels right-align instead of the default left-align.

    Source code(tar.gz)
    Source code(zip)
  • v0.2.1(Nov 19, 2019)

  • v0.2.0(Oct 20, 2018)

  • v0.1.4(Sep 23, 2018)

    • PR #31 - Fix to normalize method, division by zero error. Props to @ocozalp

    • PR #32 - Fix vertical graphs, missing args. Props to @joaquincasares

    • PR #32 - Do not output color character if not specified. Props to @joaquincasares

    Source code(tar.gz)
    Source code(zip)
Owner
Marcus Kazmierczak
Marcus Kazmierczak
A command line tool that builds and (re)starts your web application everytime you save a Go or template fileA command line tool that builds and (re)starts your web application everytime you save a Go or template file

# Fresh Fresh is a command line tool that builds and (re)starts your web application everytime you save a Go or template file. If the web framework yo

null 0 Nov 22, 2021
ls Xtended : A command line utility which lets you navigate through terminal like a pro 😎.

Navigate through terminal like a pro ?? ?? Demo • ⚗️ Installation • ?? Contribution • ❗ Known Issues ❓ Why? It's a pain to cd and ls multiple times to

Souvik 170 Dec 14, 2022
An open-source GitLab command line tool bringing GitLab's cool features to your command line

GLab is an open source GitLab CLI tool bringing GitLab to your terminal next to where you are already working with git and your code without switching

Clement Sam 2.1k Dec 30, 2022
A command line tool to prompt for a value to be included in another command line.

readval is a command line tool which is designed for one specific purpose—to prompt for a value to be included in another command line. readval prints

Venky 0 Dec 22, 2021
A simple command line tool using which you can skip phone number based SMS verification by using a temporary phone number that acts like a proxy.

Fake-SMS A simple command line tool using which you can skip phone number based SMS verification by using a temporary phone number that acts like a pr

Narasimha Prasanna HN 754 Dec 31, 2022
A simple tool which you can use to move through your directories from the command line

Fe What is Fe ? Fe is a simple tool which you can use to move through your direc

Pranav Baburaj 8 Jan 1, 2022
🌿circumflex is a command line tool for browsing Hacker News in your terminal

??circumflex is a command line tool for browsing Hacker News in your terminal

Ben Sadeh 669 Jan 1, 2023
t is a command line tool for testing on your terminal.

t t is a command line tool for testing on your terminal. Installation $ go get github.com/yusukebe/t/cmd/t Usage Basic usage: $ t hello hello # => PA

Yusuke Wada 31 May 5, 2022
Holly🪴 o!rdr command line tool to upload replays to it from the terminal

Holly ?? o!rdr command line tool to upload replays to it from the terminal Holly is a CLI that allows you to upload osu! replays to o!rdr from the ter

sammyette 6 Apr 25, 2022
Basic command line example using golang grpc client tools

This is a basic command line interface that demonstrates using the golang GRPC API. The API is reused between dishy and the wifi router, however both

null 42 Jan 3, 2023
git-xargs is a command-line tool (CLI) for making updates across multiple Github repositories with a single command.

Table of contents Introduction Reference Contributing Introduction Overview git-xargs is a command-line tool (CLI) for making updates across multiple

Gruntwork 713 Dec 31, 2022
git-xargs is a command-line tool (CLI) for making updates across multiple GitHub repositories with a single command

git-xargs is a command-line tool (CLI) for making updates across multiple GitHub repositories with a single command. You give git-xargs:

Maxar Infrastructure 1 Feb 5, 2022
A command line tool for simplified docker volume command built with go

dockervol A command line tool for simplified docker volume command built with go. Features: Remove anonymous volume (beta) Remove volume by matching n

Moh Achun Armando 0 Dec 18, 2021
Simple command line serial terminal for the Zolatron 64

ZolaTerm Simple command line serial terminal for the Zolatron 64. Written in Go. I'm using Go routines for receiving text (so that it can be displayed

Machina Speculatrix 0 Nov 7, 2021
The sntr command-line program gives you convenient access to Sentry directly from your terminal.

sntr: all of Sentry at your fingertips The sntr command-line program gives you convenient access to Sentry directly from your terminal. Disclaimer: th

Rodolfo Carvalho 0 Jan 31, 2022
fofax is a fofa query tool written in go, positioned as a command-line tool and characterized by simplicity and speed.

fofaX 0x00 Introduction fofax is a fofa query tool written in go, positioned as

null 516 Jan 8, 2023
Go package to make lightweight ASCII line graph ╭┈╯ in command line apps with no other dependencies.

asciigraph Go package to make lightweight ASCII line graphs ╭┈╯. Installation go get github.com/guptarohit/asciigraph Usage Basic graph package main

Rohit Gupta 2.1k Jan 8, 2023
A Go package for drawing basic graphics in a terminal

Tgraph Tgraph is a Go package for drawing basic graphics in a terminal. It was inspired by termgraph. Graph types supported: Bar Graphs Multi-variable

daoleno 50 Nov 14, 2022
basic terminal based chat application written in go

this app uses websocket protocol to communicate in real time. both the client and the server are written in golang. it uses: gorilla/websocket package

Abidin Durdu 0 Nov 4, 2021