#!/usr/bin/env python3
# Plot a trig curve, horizontally.
# 2018-10-25
import shutil
import math
def trigfunc(x, scale):
y = math.sin(x) * math.cos(scale*x)
return y
#-------------------------------
def prtline(y, width):
'''
y is a value to "plot"
width is the terminal's width in characters
'''
c = 1
columns = (y+1.0) * width/2
while c <= columns:
print('*', end='')
c += 1
print('%.2f'%(y))
#-------------------------------
def makeplot(xs, ys, width, height):
''' Plot a set of x- and y-values as a horizontal
ASCII plot with dimensions 'width' columns by 'height' rows.
minimum and maximum x values are taken for the 'xs' list,
while y is assumed to range from -1.0 to 1.0
(but min. and max. y values could also be extracted from
the 'ys' list).
'''
# Calculate the Y coordinate for each row of the plot:
y_stepsize = (1.0 - -1.0) / height
y_coords = []
for row in range (0, height):
y_coords.append( 1.0 - row * y_stepsize )
# Calculate the X coordinate for each column of the plot:
x_stepsize = (xs[-1] - xs[0]) / width
x_coords = []
for col in range(0, width):
x_coords.append( round(col * x_stepsize) )
# Now plot data by filling in the plot spaces between
# the x-axis and the ys value with '*' symbols:
for row in range(height): # This could also be done as...
y = y_coords[row] # ..."for y in y_coords:"
print('%4.1f' % (y), end='') # print row label
for col in range(width): # Could also be done as...
x = x_coords[col] # ..."for x in x_coords:"
if y >= 0: # upper (positive) half of plot?
if y <= ys[x]:
print('*', end='')
else:
print(' ', end='')
else: # lower (negative) half of plot?
if y >= ys[x]:
print('*', end='')
else:
print(' ', end='')
print() # finish off the row
#-------------------------------
#-------------------------------
width = shutil.get_terminal_size()[0] - 6 # leave space for y-labels
height = shutil.get_terminal_size()[1] - 6 # leave space for x-labels, other output
print("width: %d height: %d" % (width, height))
xmax = int(input('max X value? '))
scale = float(input('scale factor? '))
print("xmax: %f scale: %f" % (xmax, scale))
x_values = []
y_values = []
step = 0.1 # adjustable constant, tweaks the "resolution" of the data
# Build the lists of x- and y-values:
for index in range(0, xmax):
x = index * step
y = trigfunc(x, scale)
x_values.append(x)
y_values.append(y)
#prtline(y, width)
makeplot(x_values, y_values, width, height)
# Older, simpler, vertical-plot loop:
#for y in y_values:
# prtline(y, width)
#-------------------------------