GithubHelp home page GithubHelp logo

termgraph's Introduction

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.7+, install from PyPI project

python3 -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] [(optional arguments)] [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
  --space-between       Print a new line after every field
  --color [COLOR ...]   Graph bar color( s )
  --vertical            Vertical graph
  --stacked             Stacked bar graph
  --histogram           Histogram
  --bins BINS           Bins of Histogram
  --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

termgraph's People

Contributors

adityataggar05 avatar aquassaut avatar danielhoherd avatar dkasak avatar dufferzafar avatar edwardbetts avatar eldipa avatar hiromuishikawa avatar jagmoreira avatar joaquincasares avatar juanafernandez avatar lebinh avatar mkaz avatar nnist avatar ocozalp avatar robertpeteuil avatar tayoogunbiyi avatar timgates42 avatar yegle avatar zkotti avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

termgraph's Issues

Use it as module

Is this module available as a third-party module? If yes, how to integrate. If not, what are your plans?

Images

A placeholder for images used in README.

calheatmap

example2

example3

--width only applies to the highest value with used with --stack

when using --stack and --width together, the width is determined by the highest single value in the series, setting all other values as a proportion of that, greatly extending the width beyond what is designated, and making it impossible to designate a desired width when working with values that are not known ahead of time.

$ cat <<EOF | termgraph --custom-tick="X" --stack --width=10
test1 10 20 40 40 40
test2 10 20 40 40 10
test3 10 10 10 10 10
EOF

test1: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 150.00
test2: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX 120.00
test3: XXXXXXXXXX 50.00

Screen Shot 2020-10-09 at 10 49 27 AM

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 63491d8), 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

Supporting network graphs

Hello!

Do you think it would be possible to also have networks displayed in the terminal with termgraph, a bit like Graphviz is doing?

Best regards

ZeroDivisionError on empty data

Background

When passing in data containing all 0's termgraph will return a ZeroDivisionError. Ideally termgraph should accept this value and return an empty graph.

Example Code

termgraph.chart(
    colors=None,
    data=[0, 0]
    args={'width': 100, 'format': '{:,}', 'suffix': '', 'no_labels': False, 'no_values': False, 'vertical': False, 'stacked': False, 'histogram': False, 'different_scale': False},
    labels=['iOS', 'Android']
)

Error Message

ERROR: Problem running script: Traceback (most recent call last):
  File "/../main.py", line 523, in <module>
    cli_handler()
  File "/.../lib/python3.8/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/.../lib/python3.8/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/.../lib/python3.8/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/.../lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/../main.py", line 194, in cli_handler
    main(
  File "/.../main.py", line 449, in main
    termgraph.chart(
  File "/.../lib/python3.8/site-packages/termgraph/termgraph.py", line 485, in chart
    normal_dat = normalize(data, args["width"])
  File "/.../lib/python3.8/site-packages/termgraph/termgraph.py", line 162, in normalize
    norm_factor = width / float(max_datum)
ZeroDivisionError: float division by zero

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'

Add to pypi?

Would be great to be able to pull this in as a dependency on some other projects. Are you interested in adding it pypi?

Is it possible to pipe in the output of sort | uniq -c?

Hello!

Is it possible to pipe in the output of sort | uniq -c?
This a basic bash one liner to get distributions.

Issues:

  • reverse order of data an label;
  • space separation

Pseudo Code

grep "^." MyFile.tsv | cut -f2 | sort | uniq -c | sort -nr yields

25401 1
23593 7
21999 0
21760 3
20276 4
19462 10
19301 8
18835 5
18413 6

Where the first column are the values, labels are after the white space.

grep "^." MyFile.tsv | cut -f2 | sort | uniq -c | sort -nr | termplot.py plots the labels (that happen to be numeric as well)

25401: ▇▇    1
23593: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇    7
21999: |    0
21760: ▇▇▇▇▇▇    3
20276: ▇▇▇▇▇▇▇▇    4
19462: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇   10
19301: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇    8
18835: ▇▇▇▇▇▇▇▇▇▇    5
18413: ▇▇▇▇▇▇▇▇▇▇▇▇    6
18406: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇    9
17906: ▇▇▇▇    2
17153: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇   14
16755: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇   13
14757: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇   12
14531: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇   11

Thank you!
Abel

Why does the histogram not show all the values in the data?

Thanks for making this tool. I am not sure if this is a bug, or I am missing something, but I wanted to bring it up.

Shouldn't the values for each of the bins add up to 3 since there are 3 rows in the data?

§ termgraph --version
termgraph v0.4.2

§ echo $'1 100\n2 200\n3 300' | termgraph --histogram

  100 – 140.0: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 1.00 
140.0 – 180.0:  0.00 
180.0 – 220.0: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 1.00 
220.0 – 260.0:  0.00 
260.0 – 300.0:  0.00 

Also, if the input has values that are same, there is an error:

§ echo $'1 100\n2 100' | termgraph --histogram

Traceback (most recent call last):
  File "/usr/local/bin/termgraph", line 10, in <module>
    sys.exit(main())
  File "/Library/Python/3.7/site-packages/termgraph/termgraph.py", line 130, in main
    chart(colors, data, args, labels)
  File "/Library/Python/3.7/site-packages/termgraph/termgraph.py", line 478, in chart
    for row in hist_rows(data, args, colors):
  File "/Library/Python/3.7/site-packages/termgraph/termgraph.py", line 217, in hist_rows
    normal_counts = normalize(count_list, args["width"])
  File "/Library/Python/3.7/site-packages/termgraph/termgraph.py", line 162, in normalize
    norm_factor = width / float(max_datum)
ZeroDivisionError: float division by zero

PEP8 and other issues

The code currently does not follow PEP8. By following the style guide, the code would be more readable, consistency would be better and it would be easier to maintain.

When I run pylint on termgraph.py, it outputs a large amount of warnings:

  • Spaces before and after () and [], i.e. parser.add_argument( '--title', help='Title of graph' ) should be parser.add_argument('--title', help='Title of graph')
  • Lines too long (should be 79 chars at maximum)
  • Lots of unused imports from wildcard imports (wildcard imports should be avoided)
  • Import order is wrong

It might also 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. Although this might better be filed as a new issue.

Overwrite labels

Hi, thanks a ton for this nifty package !

It'd be useful if we could overwrite the individual bar labels.

echo "Label,3,9,1" | termgraph --custom-tick "😀" --no-label  --row-values {three, nine, whatever}

Would output:

😀😀😀 three
😀😀😀😀😀😀😀😀😀 nine
😀 whatever

Alternatively, one could provide custom suffixes for each row (currently one can only append a single suffix to all rows).

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

[FR] Make termgraph can plot histogram

I want to plot histogram by Termgraph.

When I want to visualize some data, I often want to see the distribution by histogram.
So, given the use case of termgraph, I think it is the function we want

Example of histogram by Pandas is as follow:

data = np.random.normal(10, 10, 1000) # generate dummy data follow normal distribution
df = pd.DataFrame({'col': data})
df.hist()

normalhist

My expected output example in termgraph is as follow:

$ termgraph hist.dat --histogram --bins 5
-20 - -10: ▇▇▇▇▇▇▇ 7
-10 -   0: ▇▇▇▇▇▇▇▇▇ 9
  0 -  10: ▇▇▇▇▇▇▇▇▇▇▇ 11
 10 -  20: ▇▇▇▇▇▇▇▇▇ 9
 20 -  30: ▇▇▇▇▇▇▇ 7

If it is good, I will work on this function and make a PR.

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.

to solve the over length of bar problem

to solve the over length of bar problem for me (as i have really big number in prediction)
it's about the find_max function , the original function only find the biggest number in target array, so i change the fucnction to:

def find_max(list_):
    """Return the maximum value in sublist of list."""
    m1=max([sublist[-1] for sublist in list_])
    m2 = max([sublist[0] for sublist in list_])
    return max([m1,m2]) 

and solved my problem :)

Line after 0 grayed out

Why in horizontal bar chart line following 0.0 value Is grey out?

image

Here's example to reproduce the problem:

from termgraph.termgraph import chart

data = [[0],[34], [2]]
labels = ["Cars", "Boats", "Planes"]
args = {
    "histogram": False,
    "stacked": False,
    "width": 50,
    "no_labels": False,
    "no_values": False,
    "format": "{:.0f}",
    "suffix": "",
    "vertical": False
}
chart(None, data, args, labels)

Progressive Graph on Reading Each Data

Hey there. So I was wondering if there are some way to make the graph become progressive, since it reads new data on the new next line in a file. Here is my snippet on the Bash script.

#!/bin/bash
while IFS= read -r each_stat; do
  echo "$each_stat" > "log/each_result.csv" & wait
  termgraph "log/each_result.csv" --color {cyan,red,yellow,green}; sleep 0.01s
  printf "\033[6A ";
done < "log/result.csv"

First I passed each line of the file to a temp file, so termgraph can read only one data at a time. then I return the cursor 6 line before and continue to read the next data. But its not updating the bar quite what I wanted to, which become overlapped with the previous bar. Are there any solution to overwrite the previous one, without clearing the screen ?

Thanks for the opportunity, really cool stuff !

image
image
image

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

UnicodeEncodeError: 'latin-1' codec can't encode character '\u2587' in position 0: ordinal not in range(256)

Screenshot_20191004_145451

Hey, I am facing following issue when trying too tun termgraph. Problem could be with my terminal setting but I am unsure how to debug it. Kindly help

Traceback (most recent call last):
  File "/home/avi/.local/bin/termgraph", line 10, in <module>
    sys.exit(main())
  File "/home/avi/.local/lib/python3.7/site-packages/termgraph/termgraph.py", line 151, in main
    chart(colors, data, args, labels)
  File "/home/avi/.local/lib/python3.7/site-packages/termgraph/termgraph.py", line 394, in chart
    print_row(*row)
  File "/home/avi/.local/lib/python3.7/site-packages/termgraph/termgraph.py", line 255, in print_row
    sys.stdout.write(TICK)
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2587' in position 0: ordinal not in range(256)

Environment details

Install via pip3 install termgraph. Running termgraph --help works fine

SHELL : fish, version 3.0.2

OS debian linux

Distributor ID: Parrot
Description:    Parrot GNU/Linux 4.7
Release:        4.7
Codename:       n/a

Expected

termgraph should run on linux shell without problem

Actual

termgraph throws error UnicodeEncodeError: 'latin-1' codec can't encode character '\u2587' in position 0: ordinal not in range(256)

Steps

  1. Install termgraph using pip3 tool
  2. Clone termgraph repo and cd to /data directory
  3. Try to run examples termgraph ex1.dat etc

Color codes are maybe wrong

I was just testing and running things with termgraph when I noticed that the colors of the graphs seemed a little off. I thought it might the color scheme of Windows Terminal. But on further checking, I found out that the color codes in colorama.Fore and the ones in termgraph are different. Below is the code I ran for checking it.

image

I hope you update the colors accordingly if needed.

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.

Argument --no-title does not work

File README.md mentioned several examples, and the ones contains argument --no-title are not functioned as expected.

$ echo "Label,3,9,1" | termgraph --custom-tick "😀" --no-title --no-labels
termgraph: error: unrecognized arguments: --no-title

Error when using vertical flag

Hi,

I'm seeing the following error when I try and graph this data vertically using the --vertical cli flag. If I run it without the vertical flag it works fine.

Data:

12/05/2020,3
13/05/2020,10
14/05/2020,14
15/05/2020,22
16/05/2020,17
17/05/2020,19
18/05/2020,24

Command:

termgraph data.csv --vertical

Error:

Traceback (most recent call last):
  File "/Users/james/.local/share/virtualenvs/metrics-aYLqKSM2/bin/termgraph", line 8, in <module>
    sys.exit(main())
  File "/Users/james/.local/share/virtualenvs/metrics-aYLqKSM2/lib/python3.8/site-packages/termgraph/termgraph.py", line 161, in main
    chart(colors, data, args, labels)
  File "/Users/james/.local/share/virtualenvs/metrics-aYLqKSM2/lib/python3.8/site-packages/termgraph/termgraph.py", line 424, in chart
    vertic = vertically(*row, args=args)
TypeError: vertically() got multiple values for argument 'args'

I'm using Python v3.8.2 and termgraph v0.2.2.

Let me know if there's any more info I can provide.

Give the option to output an aligned chart

It could be nice to have the option to format the output as left-aligned, based on labels length or given fixed width. It makes comparisons and overall output easier to read imo

Basic suggested impl:

def horiontal_rows( labels, data, normal_dat, args, colors ):
    val_min = findMinMax( data, 'min' )
    
    # Find longest label for aligned output
    length_min = 0
    for i in range(len(labels)):
        if len(labels[i]) > length_min:
            length_min = len(labels[i])

    for i in range( len( labels ) ):
        if args['no_labels']:
            # Hide the labels.
            label = ''
        else:
            label = "{:<{x}}: ".format( labels[i], x = length_min )

...

Before:
image

After:
image

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:

odit@atlas: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/python@2/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

instructions for contributing

Specifically, how to set up project locally (install deps, run tests). I'm used to setting up apps, not libraries, so my background is using requirements.txt or pyproject.toml and pip or Poetry to install those deps, so apologies if this issue covers something that would be obvious to a library developer.

Show int as int not float

I'm using print_blocks in a script and only passing integers to it, but it always format it with decimal places.

TICK in Windows 10 (power shell) looks like small question marks ?

I am using Chart to show a bar graph and the individual "TICK" marks show up as question mark. Been trying to debug it and I was able to make it work when I change TICK from the defined quoted value to

TICK = u"\u2588"

At that point I get a solid color block in whatever color defined. I tried to

from termgraph import termgraph as tg
from collections import defaultdict
C = tg.AVAILABLE_COLORS

 TICK = u"\u2588"

    tg.chart (
        colors=[C["green"] , C["yellow"]] ,
        data=[[nft , og]] ,
        args=defaultdict (bool ,
            {
                "stacked" : True ,
                "custom_tick": TICK,
                "width" : 60 ,
                "format" : "{:<5.2f}" ,
                "no_labels" : True ,
                "suffix" : f" (NFT:{nft} ({nft_pct:.0f}%), OG:{og} ({og_pct:.0f}%))"
            } ,
        ) ,
        labels=[""] ,
    )

and the class would not reflect the overwrite of the TICK variable passed. I reviewed the code of the library and the TICK is a global value that is changed when is passed via the argument, but not when I import the package.

What do you recommend is the best approach to fix the definition of TICK so that it will show properly in windows 10.

-- Adonis

Vertical graph not rendering?

First of all: thank you so much for this neat library, appreciate all the work that has gone into making this :)

I am trying to make a graph from within another Python script, and here's a working version:

In [1]: from termgraph.termgraph import stacked_graph, AVAILABLE_COLORS, normalize, chart
   ...: 
   ...: labels = ["size 1", "size 10", "size 100"]
   ...: data = [
   ...:     [1, 1, 10],
   ...:     [1, 10, 100],
   ...:     [1, 100, 120],
   ...: ]
   ...: colors = [
   ...:     AVAILABLE_COLORS.get("green"),
   ...:     AVAILABLE_COLORS.get("yellow"),
   ...:     AVAILABLE_COLORS.get("red"),
   ...: ]
   ...: args = {
   ...:     "no_labels": False,
   ...:     "format": "{:<5.2f}",
   ...:     "suffix": "",
   ...:     "stacked": False,
   ...:     "histogram": False,
   ...:     "width": 50,
   ...:     "different_scale": False,
   ...:     "no_values": False,
   ...:     "vertical": False,
   ...: }
   ...: chart(colors, data, args, labels)
size 1  : ▏ 1.00 
          ▏ 1.00 
          ▇▇▇▇ 10.00
size 10 : ▏ 1.00 
          ▇▇▇▇ 10.00
          ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 100.00
size 100: ▏ 1.00 
          ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 100.00
          ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 120.00

However, if I change args["vertical"] to True, I get ...

In [2]: args["vertical"] = True
   ...: chart(colors, data, args, labels)
   ...: 

(no output)

Maybe I am switching up args weirdly or something, looked through the Readme and I may have missed any misc. requirements for vertical. Appreciate any help, will keep digging though!

EDIT

Of course as soon as I post this I find...

https://github.com/mkaz/termgraph/blob/main/termgraph/termgraph.py#L465

Adding "different_scale": True, made something print, but it seems rather broken.

BrokenPipeError when piping to head

Description

When piping termgraph to head, and I assume other commands that do not process the whole pipe stream, a BrokenPipeError is raised.

How to reproduce

$ cat <<EOF | termgraph | head -n 5
2021-05-30      15
2021-05-29      20
2021-05-28      21
2021-05-27      19
2021-05-26      19
2021-05-25      18
2021-05-24      18
2021-05-23      19
2021-05-22      19
EOF

2021-05-30: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 15.00
2021-05-29: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 20.00
2021-05-28: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 21.00
2021-05-27: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 19.00
Traceback (most recent call last):
  File "/home/dho/.local/bin/termgraph", line 8, in <module>
    sys.exit(main())
  File "/home/dho/.local/lib/python3.8/site-packages/termgraph/termgraph.py", line 130, in main
    chart(colors, data, args, labels)
  File "/home/dho/.local/lib/python3.8/site-packages/termgraph/termgraph.py", line 487, in chart
    for row in horiz_rows(
  File "/home/dho/.local/lib/python3.8/site-packages/termgraph/termgraph.py", line 282, in horiz_rows
    print(label, end="")
  File "/usr/lib/python3/dist-packages/colorama/ansitowin32.py", line 41, in write
    self.__convertor.write(text)
  File "/usr/lib/python3/dist-packages/colorama/ansitowin32.py", line 162, in write
    self.write_and_convert(text)
  File "/usr/lib/python3/dist-packages/colorama/ansitowin32.py", line 190, in write_and_convert
    self.write_plain_text(text, cursor, len(text))
  File "/usr/lib/python3/dist-packages/colorama/ansitowin32.py", line 196, in write_plain_text
    self.wrapped.flush()
BrokenPipeError: [Errno 32] Broken pipe
Exception ignored in: <colorama.ansitowin32.StreamWrapper object at 0x7f9016207310>
BrokenPipeError: [Errno 32] Broken pipe

Test env

$ termgraph --version
termgraph v0.4.2
$ python3 --version --version
Python 3.8.5 (default, Jan 27 2021, 15:41:15)
[GCC 9.3.0]
$ uname -a
Linux litten 5.4.0-73-generic #82-Ubuntu SMP Wed Apr 14 17:39:42 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

Stacked width inconsistent

Hi there,

Thank you very much for providing this library!

I'm attempting to use it to print a live indicator as a debugging aid. (I'm charting how much GPU memory is used vs free). I'm setting width=60 on every call. However, the total bar width changes when the data changes!

image

I'm wondering if the issue is with normalization not accounting for stacked charts?

In case it helps, here's how I'm calling it:

from collections import defaultdict
import time

from gpustat import core as gpus
from termgraph import termgraph


C = termgraph.AVAILABLE_COLORS


while True:
    # Settings
    gpu_idx = 7  # TODO: cmd line

    info = gpus.new_query()
    gpu = info[gpu_idx]

    termgraph.chart(
        colors=[C["red"], C["yellow"]],
        data=[[gpu.memory_used, gpu.memory_free]],
        args=defaultdict(
            bool,
            {
                "stacked": True,
                "width": 60,
                "format": "{:<5.2f}",
                "no_labels": True,
                "suffix": f" (used: {gpu.memory_used}, free: {gpu.memory_free})",
            },
        ),
        labels=[""],
    )

    time.sleep(1)

Many thanks for any tips, and apologies if I'm confused here!

Question regarding the format specifier

Hi.

I am trying to create some stacked bar graphs, using integer values. However, the default format is 5.2f float. trying to override that with e.g. 3d literally prints out the 3d to the r.h.s of each bar. See the attached figure.

How can I show integral values on the graph?

Thanks
Ehsan
image

Few questions and feature requests

Hi.

I am quite enjoying termgraph; so, first of all, thanks for sharing this nice tool.

I've got few questions and perhaps feature requests.

  • In the attached (draft) figure, every bar adds up to 100%, because the values are in percentage. Therefore, it does not make sense to print the sum (i.e. "100") to the right of each bar, anymore. Is there a way to suppress it (e.g. via args)?

  • Sometimes a row contains zeros, e.g. for "superdome" the values are basically a 100 and bunch of zeros. Is that the reason that the rightmost end of all rows do not line up? Is there a way to fix this?

  • There are two newline spaces between the category printout and the actual bars. Is it possible to let the user decide this (via args)?

Kind regards
Ehsan

image

Documentation to use termgraph as python module within python script

Hi, is there any documentation for how to use termgraph within a .py script instead of on the terminal? Was searching for any form of documentation online, and I found the following code which works, thus I was wondering how I could do the same on a .py script for horizontal graphs:

from termgraph import termgraph as tg

labels = ['2007', '2008', '2009', '2010', '2011', '2012', '2014']
data = [[183.32, 190.52], [231.23, 5.0], [16.43, 53.1], [50.21, 7.0], [508.97, 10.45], [212.05, 20.2], [30.0, 20.0]]
normal_data = [[48.059508408796894, 50.0], [60.971862871927556, 0.0],
[3.080530401034929, 12.963561880120743],
[12.184670116429496, 0.5390254420008624],
[135.82632600258734, 1.4688443294523499],
[55.802608883139285, 4.096593359206555],
[6.737818025010781, 4.042690815006468]]
len_categories = 2
args = {'filename': 'data/ex4.dat', 'title': None, 'width': 50,
'format': '{:<5.2f}', 'suffix': '', 'no_labels': True,
'color': None, 'vertical': False, 'stacked': True,
'different_scale': False, 'calendar': False,
'start_dt': None, 'custom_tick': '', 'delim': '',
'verbose': False, 'version': False}
colors = [91, 94]
tg.stacked_graph(labels, data, normal_data, len_categories, args, colors)

Could there be a support for pie-charts in termgraph?

Hello, awesome folks developing termgraph.
I have recently build a utility which displays useful git information in a presentable colored graphs (of course using termgraph) on terminal. I am really enjoying the reports :)

Wanted to check if there is any support for pie-charts (like this project) is planned for the future releases or not ??

Since I enjoy this tool so much, I am willing to spend some time on it and maybe prepare a feature request for it myself, but I might need some help and guidance :D Free free to drop the plan in comments as to how such a feature could be implemented in this project.

Thanks and cheers

A flag to swap labels and values in the input (Unix "uniq" compatibility)

Termgraph looks like an amazing tool and it could be really useful for some ad-hoc investigations.

When looking at the logs and other texts it's often useful to run some-command | sort | uniq -c which counts unique entries and prints the list of unique values and the number of occurrences. For example:

     16 alter
     17 create
     15 drop
     12 insert
      8 update

Termgraph would fit nicely into this use case, like some-command | sort | uniq -c | termgraph. The issue is that termgraph always expects the label to go first. Of course in the example above it can be solved with Awk for example (like | awk '{print $2, $1}', however first of all it's an extra step (which reduces usability), and also it makes it problematic if the label contains a space.

That said, it would be awesome to have a CLI flag for termgraph like --values-first, which would tell termgraph to read the value in the first column and use the rest of the line as a label.

It would allow termgraph to be used seamlessly in the example above and also provide extra flexibility in other use cases which can use a similar input format

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.