plot_by_index.py 1.68 KB
Newer Older
d3k2mk7's avatar
d3k2mk7 committed
1 2 3 4 5 6 7 8
#! /usr/bin/env python3

# plot a column of data read from stdin.

import sys
import pandas as pd
import matplotlib.pyplot as plt

9 10
import os

11

d3k2mk7's avatar
d3k2mk7 committed
12 13 14
def parse_arguments(args):
    import argparse
    parser = argparse.ArgumentParser(
d3k2mk7's avatar
d3k2mk7 committed
15
        description='Plot a column of data read from stdin')
d3k2mk7's avatar
d3k2mk7 committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

    parser.add_argument(
        "--header", action='store_true',
        dest='header',
        help='use 1st line as header')
    parser.add_argument(
        "--no-header", action='store_false',
        dest='header',
        help='assumes that there is no header')
    parser.set_defaults(header=True)

    parser.add_argument(
        "--debug", action='store_true',
        default=False, dest='debug',
        help='show debug output. Default is false.')
    res = parser.parse_args(args)
    if res.debug:
        print(res)
    return res


# y is a pandas.core.series.Series
# ylabel is a string
def plot_col_by_index(y, ylabel):
d3k2mk7's avatar
d3k2mk7 committed
40
    plt.figure(figsize=(8, 6))
d3k2mk7's avatar
d3k2mk7 committed
41 42 43 44 45 46 47
    plt.scatter(range(y.shape[0]), y)
    plt.title('plot by Index')
    plt.xlabel('index', fontsize=12)
    plt.ylabel(ylabel, fontsize=12)
    plt.grid()
    plt.show()

48

d3k2mk7's avatar
d3k2mk7 committed
49 50
if __name__ == "__main__":
    args = parse_arguments(sys.argv[1:])
51

d3k2mk7's avatar
d3k2mk7 committed
52
    header = args.header
53

d3k2mk7's avatar
d3k2mk7 committed
54
    # Do all the plotting in the background
55 56 57 58
    # Ref:- https://stackoverflow.com/questions/12467280/how-can-i-tell-python-to-end-after-pylab-show
    if os.fork():
        # Parent
        pass
d3k2mk7's avatar
d3k2mk7 committed
59
    else:
60 61 62 63
        # Child
        os.setsid()
        if (header):
            df = pd.read_csv(sys.stdin)
d3k2mk7's avatar
d3k2mk7 committed
64
            plot_col_by_index(df[df.columns[0]], df.columns[0])
65 66
        else:
            df = pd.read_csv(sys.stdin, header=None)
d3k2mk7's avatar
d3k2mk7 committed
67
            plot_col_by_index(df[df.columns[0]], 'data')