Skip to content

Commit cc98c56

Browse files
committed
Fix constant plot error
Plots with constant-only X or Y values encountered div by zero error. Also make those plots nicer with some space above and below, left and right of plotting area. Fixes #1
1 parent aa4d17a commit cc98c56

File tree

2 files changed

+38
-6
lines changed

2 files changed

+38
-6
lines changed

plotille.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,15 +119,31 @@ def plot(X, Y, width=80, height=50, X_label='X', Y_label='Y', linesep=os.linesep
119119
if interp == 'linear':
120120
interp_fktn = _interp_lin
121121

122-
ymin = min(Y) if len(Y) > 0 else 0
123-
ymax = max(Y) if len(Y) > 0 else 1
124-
xmin = min(X) if len(X) > 0 else 0
125-
xmax = max(X) if len(X) > 0 else 1
122+
ymin = 0
123+
ymax = 1
124+
if len(Y) > 0:
125+
ymin = min(Y)
126+
ymax = max(Y)
127+
# have some space above and below the plot
128+
offset = max(abs(ymax), abs(ymin)) / 10
129+
ymin -= offset
130+
ymax += offset
131+
132+
xmin = 0
133+
xmax = 1
134+
if len(X) > 0:
135+
xmin = min(X)
136+
xmax = max(X)
137+
# have some space above and below the plot
138+
offset = max(abs(xmax), abs(xmin)) / 10
139+
xmin -= offset
140+
xmax += offset
126141

127142
xwidth = abs((xmax - xmin) / width)
128-
xwidth_p = xwidth / 2
129143
ywidth = abs((ymax - ymin) / height)
130-
ywidth_p = ywidth / 4
144+
# no devision by zero
145+
xwidth_p = xwidth / 2 or 1
146+
ywidth_p = ywidth / 4 or 1
131147

132148
canvas = _init(width, height)
133149

tests/test_plot.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# -*- coding: utf-8 -*-
2+
from __future__ import division, print_function, unicode_literals
3+
4+
from plotille import plot
5+
6+
7+
def test_constant_y():
8+
print(plot([1, 4], [0.5, 0.5]))
9+
10+
11+
def test_constant_x():
12+
print(plot([0.5, 0.5], [1, 4]))
13+
14+
15+
def test_constant_x_y():
16+
print(plot([0.5, 0.5], [0.5, 0.5]))

0 commit comments

Comments
 (0)