Beispiel #1
0
def show_points(
    points: t.Sequence[t.Tuple[datetime.datetime, t.Union[int, float]]],
    title: str,
    y_label: str,
) -> None:
    if not points:
        print('No data')
        return

    import plotext as plt

    dates, values = zip(*points)
    date_time_stamps = [d.timestamp() for d in dates]

    plt.plot(date_time_stamps, values)
    plt.xticks(date_time_stamps, (d.strftime('%Y/%m/%d') for d in dates))
    plt.title(title)
    plt.xlabel('Date')
    plt.ylabel(y_label)
    plt.ylim(0, max(values) * 1.1)
    plt.canvas_color('iron')
    plt.axes_color('cloud')
    plt.grid(False, True)

    plt.show()
Beispiel #2
0
    def plot_coverage(self, sequence_name, coverage, num_bins=100):
        try:
            import plotext as plt
        except:
            self.run.warning(
                "You don't have the `plotext` library to plot data :/ You can "
                "install it by running `pip install plotext` in your anvi'o "
                "environment.",
                header="NO PLOT FOR YOU :(")

            return

        plt.clp()
        plt.title(f"{sequence_name}")
        plt.xlabel("Position")
        plt.ylabel("Coverage")
        plt.plot(coverage, fillx=True)
        plt.plotsize(self.progress.terminal_width, 25)
        plt.canvas_color("cloud")
        plt.axes_color("cloud")
        plt.ticks_color("iron")

        try:
            plt.show()
        except OSError:
            self.run.warning(
                "Redirecting things into files and working with funny TTYs confuse "
                "the plotting services. Is ok tho.",
                header="NO PLOT FOR YOU :(")
            pass
Beispiel #3
0
def print_plot(items,
               x,
               y=None,
               sort=None,
               fillx=False,
               title=None,
               grid=False,
               marker=None,
               color=None,
               background_color=None,
               axes_color=None):
    df = items_to_dataframe(items, sort=sort)
    x_list = df[x].tolist()
    y_list = df[y].tolist() if y else None
    _x = df['timestamp'].tolist() if x in DATE_FIELDS else df[x]

    if y is None:
        plt.scatter(_x, marker=marker, color=color, fillx=fillx)
    else:
        plt.plot(_x, y_list, marker=marker, color=color, fillx=fillx)
        plt.xticks(_x, x_list)

    if title is not None:
        plt.title(title)

    if grid:
        plt.grid(True, True)

    if background_color is not None:
        plt.canvas_color(background_color)
        plt.axes_color(background_color)
    if axes_color is not None:
        plt.ticks_color(axes_color)

    plt.show()
Beispiel #4
0
    def plot(self, include, in_terminal=False):
        """
    Plot relevant variables in a flexible manner.

    Parameters
    ----------
    include : list
      The list of plots to include.
    in_terminal : bool, default=False
      If True, shows plots in terminal, giving an oldschool NASA vibe. If False, uses boring matplotlib. 
    """
        if in_terminal:
            import plotext as plt
        else:
            import matplotlib.pyplot as plt

        for plot in include:
            x_log = self.logs[plot['x']['logname']]
            x_data = x_log.get_data(plot['x']['ops'])

            y_log = self.logs[plot['y']['logname']]
            y_data = y_log.get_data(plot['y']['ops'])

            if in_terminal:
                plt.clear_plot()
                plt.nocolor()
                plt.figsize(75, 25)
            else:
                plt.figure()
            plt.plot(x_data, y_data)
            plt.show()
Beispiel #5
0
def plot_wkt(wkt_string):
    """
    Plot a WKT string describing a polygon
    """
    from shapely import wkt
    plt = import_plt()
    poly = wkt.loads(wkt_string)
    coo = numpy.array(poly.exterior.coords)
    plt.plot(coo[:, 0], coo[:, 1], '-')
    return plt
Beispiel #6
0
def main():
    parser = argparse.ArgumentParser()

    # adding the arguments
    parser.add_argument(
        "-e", default=datetime.today().isoformat(timespec='hours')[:-3])
    parser.add_argument("-t", default='1y')
    parser.add_argument("-i", default='^GDAXI')

    # Parse and print the results
    args = parser.parse_args()
    print(args)

    # compute timeframe
    if args.t == '1y':
        timeframe = timedelta(days=365)
    elif args.t == '5y':
        timeframe = timedelta(days=365 * 5)
    elif args.t == '10y':
        timeframe = timedelta(days=365 * 10)
    elif args.t == '6m':
        timeframe = timedelta(days=30 * 6)
    elif args.t == '3m':
        timeframe = timedelta(days=30 * 3)
    elif args.t == '1m':
        timeframe = timedelta(days=30)
    else:
        timeframe = timedelta(days=365)

    tickerSymbol = args.i
    end = args.e
    start = (datetime.fromisoformat(end) -
             timeframe).isoformat(timespec='hours')[:-3]

    # getting the financial data from yfinance
    tickerData = yf.Ticker(tickerSymbol)

    # selecting the correct timeperiod
    tickerDf = tickerData.history(period='1s', start=start, end=end)

    start = datetime.fromisoformat(start)
    end = datetime.fromisoformat(end)

    # plotting the data green if overall close goes up and red if down
    if tickerDf.iloc[0]['Close'] < tickerDf.iloc[-1]['Close']:
        plx.plot(drange(start, end, timedelta(days=1)),
                 tickerDf['Close'],
                 line_color='green')
    else:
        plx.plot(drange(start, end, timedelta(days=1)),
                 tickerDf['Close'],
                 line_color='red')

    plx.show()
Beispiel #7
0
 def set_plot(self, earnings, times):
     y = earnings
     x = times
     listofzeros = [0] * len(earnings)
     ptt.plot(y, line_color='red')
     ptt.plot(listofzeros, line_color='green')
     ptt.ylim(-500, -250)
     ptt.grid(True)
     ptt.canvas_color("black")
     ptt.axes_color("black")
     ptt.ticks_color("cloud")
     ptt.show()
Beispiel #8
0
def plot_measures(measures, offset=0):
    start_timestamp = datetime.now() - timedelta(days=7)
    now = datetime.now()

    width, height = plt.terminal_size()

    if offset:
        height -= offset

    if MAXIMUM_HEIGHT and MAXIMUM_HEIGHT < height:
        height = MAXIMUM_HEIGHT

    if MAXIMUM_WIDTH and MAXIMUM_WIDTH < width:
        width = MAXIMUM_WIDTH

    values_y = [m.value for m in measures]
    values_x = [m.timestamp for m in measures]

    plt.clear_plot()
    plt.plot(values_x, values_y)
    plt.nocolor()

    xticks = [int(start_timestamp.strftime("%s"))]
    xlabels = [start_timestamp.strftime(DATETIME_FORMAT)]

    day = (start_timestamp + timedelta(days=1)).replace(hour=0,
                                                        minute=0,
                                                        second=0,
                                                        microsecond=0)

    while day < now:
        xticks.append(int(day.strftime("%s")))
        xlabels.append(day.strftime(DATETIME_FORMAT))

        day += timedelta(days=1)

    plt.xlim(int(start_timestamp.strftime("%s")), int(now.strftime("%s")))

    plt.xticks(xticks, xlabels)
    plt.figsize(width, height)

    plt.show()
Beispiel #9
0
 def metrics(self):
     # available metrics
     metrics = ('node_cpu_usage', 'node_memory_usage', 'node_disk_usage',
                'pod_memory_usage', 'pod_cpu_usage')
     # column in prom2df dataframe for given metric group
     metric_group_column = {
         'node': 'node',
         'pod': 'pod_name',
     }
     metric_name = (self.args.get('<metric_name>') or '').replace('-', '_')
     since = self.args.get('--since') or None
     start = self.args.get('--start') or None
     end = self.args.get('--end') or None
     step = self.args.get('--step') or None
     should_plot = self.args.get('--plot')
     # check if we have a valid metric
     if metric_name in metrics:
         # get default range, if any
         if since:
             if any(since.endswith(v) for v in 'hms'):
                 # a relative time spec
                 unit = dict(h='hours', m='minutes',
                             s='seconds').get(since[-1])
                 delta = int(since[0:-1])
                 start = datetime.utcnow() - timedelta(**{unit: delta})
             else:
                 # absolute time
                 start = pd.to_datetime(since, utc=True)
         if start:
             start = pd.to_datetime(start, utc=True)
         if end:
             end = pd.to_datetime(end, utc=True)
         if start and not end:
             end = datetime.utcnow()
         if end and not start:
             start = (end - timedelta(minutes=10)).isoformat()
         if (start or end) and not step:
             step = '5m'
         # query
         om = self.om
         auth = self._restapi_auth()
         data = self._get_metric(metric_name,
                                 auth,
                                 start=start,
                                 end=end,
                                 step=step)
         try:
             df = prom2df(data['objects'], metric_name)
         except:
             print("No data could be found. Check the time range.")
             return
         if should_plot:
             import plotext as plx
             # as returned by plx.get_colors
             colors = 'red', 'green', 'yellow', 'organge', 'blue', 'violet', 'cyan'
             metric_group = metric_group_column[metric_name.split('_',
                                                                  1)[0]]
             for i, (g, gdf) in enumerate(df.groupby(metric_group)):
                 x = range(0, len(gdf))
                 y = gdf['value'].values
                 plx.plot(x, y, line_color=colors[i])
             plx.show()
         else:
             print(tabulate(df, headers='keys'))
     else:
         print("Available metrics:", metrics)
Beispiel #10
0
import sys
import plotext as plt

# format: <<ID:default_value>>
labels = <<LABELS:None>>
h = <<HEIGHT:None>>
w = <<WIDTH:None>>
vv = <<DATA:[]>>

for ii in range(len(vv)):
    v = vv[ii]
    label=""
    if labels and ii < len(labels):
        label = labels[ii]
        plt.plot(v, label=label)
    else:
        plt.plot(v)

plt.canvas_color('black')
plt.axes_color('black')
plt.ticks_color('white')
if w is not None:
    plt.plot_size(w, h)
plt.show()
Beispiel #11
0
'''
small auxiliary script that uses the lammps log parser to quickly plot data
to terminal

usage:
plot_thermo.py <thermo_key>
'''

import lammps_log_parser as lmp
import plotext as pt
import sys

yvar = sys.argv[1]

data = lmp.parse_log_to_pandas_df('*log')
pt.plot(data['Step'], data[yvar])

pt.xlabel('simulation steps')
pt.ylabel(yvar)
pt.nocolor()
pt.figsize(160, 40)

pt.show()