Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/plotext/_global.py: 10%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file contains some plotext functions which are only available to the top main level and not to sub figures (which are written in _figure.py and _monitor.py). These are functions which requires some coding and would be too long to be added directly in _core.py
3from plotext._utility import marker_codes, hd_symbols, sin
4from plotext._figure import _figure_class
5from plotext._utility import themes as _themes
6import plotext._utility as ut
7from time import time, sleep
8from math import sqrt, ceil
9import datetime as dt
11figure = _figure_class() # the main figure at top level
13##############################################
14####### Simple Bar Functions ########
15##############################################
17def simple_bar(*args, width = None, marker = None, color = None, title = None):
18 x, y = ut.set_data(*args)
19 marker = ut.correct_marker(marker)
21 color_ok = ut.is_color(color) or (isinstance(color, list) and len(color) == len(x))
22 color = [color] if color_ok else None
24 simple_stacked_bar(x, [y], width = width, marker = marker, colors = color, title = title)
26def simple_stacked_bar(*args, width = None, marker = None, colors = None, title = None, labels = None):
27 x, y, Y, width = ut.bar_data(*args, width = width)
28 marker = ut.correct_marker(marker)
30 bars = len(Y); stacked_bars = len(Y[0])
32 colors_ok1 = isinstance(colors, list) and isinstance(colors[0], list) and ut.matrix_size(colors) == [bars, stacked_bars]
33 colors_ok2 = isinstance(colors, list) and len(colors) == stacked_bars
34 colors = ut.transpose(colors) if colors_ok1 else [colors] * bars if colors_ok2 else [ut.color_sequence[:stacked_bars]] * bars
36 title = ut.get_title(title, width)
37 bars = [ut.single_bar(x[i], Y[i], y[i], marker, colors[i]) for i in range(bars)]
38 labels = ut.get_simple_labels(marker, labels, colors[0], width)
39 figure.monitor.matrix.canvas = title + '\n'.join(bars) + labels
40 figure.monitor.fast_plot = True
42def simple_multiple_bar(*args, width = None, marker = None, colors = None, title = None, labels = None):
43 x, y, Y, width = ut.bar_data(*args, width = width, mode='multiple')
44 bars = len(Y); multiple_bars = len(Y[0]); lx = len(x[0])
45 marker = ut.correct_marker(marker)
47 colors_ok = isinstance(colors, list) and len(colors) == multiple_bars
48 colors = colors if colors_ok else ut.color_sequence[:multiple_bars]
50 out = ut.get_title(title, width)
51 for i in range(bars):
52 xn = [x[i] if j == (multiple_bars - 1) // 2 else ut.space * lx for j in range(multiple_bars)]
53 new = [ut.single_bar(xn[j], [Y[i][j]], y[j][i], marker, [colors[j]]) for j in range(multiple_bars)]
54 out += '\n'.join(new)
55 out += '\n\n' if i != bars - 1 else ''
56 labels = ut.get_simple_labels(marker, labels, colors, width)
57 figure.monitor.matrix.canvas = out + labels
58 figure.monitor.fast_plot = True
60##############################################
61############# Play GIF ################
62##############################################
64def play_gif(path):
65 from PIL import Image, ImageSequence
66 path = ut.correct_path(path)
67 if not ut.is_file(path):
68 return
69 im = Image.open(path)
70 index = 1
71 for image in ImageSequence.Iterator(im):
72 load_time = time()
73 figure.clt()
74 image = image.convert('RGB')
75 figure.monitor._draw_image(image, fast = True)
76 figure.show()
77 load_time = time() - load_time
78 frame_time = image.info['duration'] / 10 ** 3
79 if load_time < frame_time:
80 sleep(frame_time - load_time)
82##############################################
83########## Video Functions ############
84##############################################
86def play_video(path, from_youtube = False):
87 path = ut.correct_path(path)
88 if not ut.is_file(path):
89 return
90 _play_video(path, from_youtube)
92def play_youtube(url):
93 import pafy
94 video = pafy.new(url)
95 best = video.getbest()
96 _play_video(best.url, from_youtube = True)
98def get_youtube(url, path, log):
99 import pafy
100 video = pafy.new(url)
101 best = video.getbest(preftype = "mp4")
102 path = "youtube-video.mp4" if path is None else path
103 path = ut.correct_path(path)
104 best.download(filepath = path, quiet = not log)
105 print(ut.format_strings('YouTube video downloaded as', path)) if log else None
107def _play_video(path, from_youtube = False):
108 import cv2
109 from ffpyplayer.player import MediaPlayer
110 from PIL import Image
111 cap = cv2.VideoCapture(path)
112 player = MediaPlayer(path)#, paused = True, loglevel = 'quiet');
113 fr = 0;
114 while fr == 0:
115 fr = cap.get(cv2.CAP_PROP_FPS)
116 frame_time = 1 / fr
117 #to_list = lambda frame: [[tuple(int(el) for el in tup) for tup in row] for row in frame]
118 pt = lambda time: '{time:05.1f} '.format(time=round(10 ** 3 * time, 1))
119 real_time = video_time = 0
120 while True:
121 load_time = time()
122 check_video, frame = cap.read();
123 audio, check_audio = player.get_frame(show = False)
124 load_time = time() - load_time
125 if not check_video:
126 break
127 if load_time >= frame_time:
128 continue
129 real_time += load_time
130 video_time += frame_time
131 show_time = 0
132 shown = False
133 if video_time >= real_time:
134 shown = True
135 show_time = time()
136 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if from_youtube else frame
137 #frame = to_list(frame)
138 image = Image.fromarray(frame)
139 figure.clt()
140 figure.monitor._draw_image(image, fast = True)
141 figure.show()
142 show_time = time() - show_time
143 sleep_time = 0
144 if real_time < video_time:
145 sleep_time = time()
146 sleep(video_time - real_time)
147 sleep_time = time() - sleep_time
148 total_time = load_time + show_time + sleep_time
149 real_time += show_time + sleep_time
150 #print('load: ' + pt(load_time), 'show: ' + pt(show_time), 'sleep: ' + pt(sleep_time), 'total: ' + pt(total_time), 'frame: ' + pt(frame_time), 'real: ' + pt(real_time), 'video: ' + pt(video_time), 'r/v:', round(real_time / video_time, 3)) if shown else None
151 player.close_player()
152 cap.release()
153 cv2.destroyAllWindows()
154 figure.clf()
156##############################################
157############ Utilities ###############
158##############################################
160test_data_url = "https://raw.githubusercontent.com/piccolomo/plotext/master/data/data.txt"
161test_bar_data_url = "https://raw.githubusercontent.com/piccolomo/plotext/master/data/bar_data.txt"
162test_image_url = "https://raw.githubusercontent.com/piccolomo/plotext/master/data/cat.jpg"
163test_gif_url = "https://raw.githubusercontent.com/piccolomo/plotext/master/data/homer.gif"
164test_video_url = "https://raw.githubusercontent.com/piccolomo/plotext/master/data/moonwalk.mp4"
165test_youtube_url = 'https://www.youtube.com/watch?v=ZNAvVVc4b3E&t=75s'
167##############################################
168######### Matplotlib Backend ##########
169##############################################
171def from_matplotlib(fig, marker = None):
172 fig.canvas.draw()
173 slots = (rows, cols) = fig.axes[0].get_subplotspec().get_gridspec().get_geometry()
174 figure.clf(); #clt()
175 figure.subplots(*slots)
176 round10 = lambda data: [round(el, 10) for el in data]
177 to_rgb = lambda rgb_norm: tuple([round(255 * el) for el in rgb_norm[:3]])
178 figure.axes_color(to_rgb(fig.patch.get_facecolor()))
179 for sub in fig.axes[:]:
180 p = sub.get_subplotspec().get_geometry()[2]
181 row = int((p - 0) / cols + 1)
182 col = p + 1 - (row - 1) * cols
183 monitor = figure.subplot(row, col)
184 monitor.xlabel(sub.get_xlabel())
185 monitor.ylabel(sub.get_ylabel())
186 monitor.title(sub.get_title())
187 monitor.xscale(sub.get_xscale())
188 monitor.yscale(sub.get_yscale())
189 monitor.xticks(round10(sub.get_xticks()))
190 monitor.yticks(round10(sub.get_yticks()))
191 monitor.canvas_color(to_rgb(sub.get_facecolor()))
192 for point in sub.collections:
193 label = point.get_label()
194 label = label if label[0] != '_' else ''
195 #point.set_offset_position('data')
196 x, y = ut.transpose(point.get_offsets())
197 color = [ut.to_rgb(point.to_rgba(el)) for el in point.get_facecolors()[0]]
198 # can't find the right point colors
199 monitor.scatter(x, y, label = label, marker = marker)
200 for line in sub.get_lines():
201 label = line.get_label()
202 label = label if label[0] != '_' else ''
203 x, y = line.get_data()
204 monitor.plot(x, y, marker = marker, color = line.get_c(), label = label)
205 for b in sub.patches:
206 label = b.get_label()
207 label = label if label[0] != '_' else ''
208 color = b.get_facecolor()
209 color = ut.to_rgb(color)
210 box = b.get_bbox()
211 x0, y0, x1, y1 = box.x0, box.y0, box.x1, box.y1
212 x = [x0, x0, x1, x1, x0]
213 y = [y0, y1, y1, y0, y0]
214 fill = b.get_fill()
215 fillx = fill if y0 == 0 else False
216 filly = fill if x0 == 0 else False
217 monitor.plot(x, y, fillx = fillx, filly = filly, marker = marker, color = color, label = label)
218 monitor.xlim(*sub.get_xlim())
219 monitor.ylim(*sub.get_ylim())
221##############################################
222####### Presentation Functions ########
223##############################################
225def markers():
226 markers = list(hd_symbols.keys())[::-1] + list(marker_codes.keys())
227 l = len(markers)
228 rows = int(sqrt(l))
229 cols = ceil(l / rows)
230 y = ut.sin(1)
231 figure.clf(); figure.theme('pro'); figure.xfrequency(0); figure.yfrequency(0); figure.frame(1)
232 figure.subplots(rows, cols)
233 figure.frame(0)
234 for row in range(1, rows + 1):
235 for col in range(1, cols + 1):
236 i = (row - 1) * cols + col - 1
237 if i < l:
238 subplot = figure.subplot(row, col)
239 figure.frame(1)
240 default = ' [default]' if markers[i] == 'hd' else ''
241 subplot.title(markers[i] + default)
242 subplot.scatter(y, marker = markers[i])
243 subplot.ticks_style('bold')
244 #figure.ticks_color(figure._utility.title_color)
245 figure.show()
246 figure.clf()
248def colors():
249 print(ut.colorize("String Color Codes", style = 'bold'))
250 bg = "default"
251 c = ut.no_duplicates([el.replace('+', '') for el in ut.colors if el not in ['default', 'black', 'white']])
252 cp = [ut.colorize(ut.pad_string(el + '+', 10), el + '+', background = bg) for el in c]
253 c = [ut.colorize(ut.pad_string(el, 10), el, background = bg) for el in c]
254 c = [' ' + c[i] + cp[i] for i in range(len(c))]
255 c = '\n'.join(c)
256 print(' ' + ut.colorize(ut.pad_string('default', 20), background = bg))
257 print(' ' + ut.colorize(ut.pad_string('black', 10), 'black', background = 'gray') + ut.colorize(ut.pad_string('white', 10), 'white', background = bg))
258 print(c)
259 print()
260 #print(colorize("\n\nInteger Color Codes:", style = ''))
261 c = ut.colorize("Integer Color Codes", style = 'bold', show = False) + '\n'
262 for row in range(16):
263 cr = ' '
264 for col in range(16):
265 i = row * 16 + col
266 cr += ut.colorize(ut.pad_string(i, 5), i)
267 c += cr + '\n'
268 print(c)
269 c = '\n'
270 rgb = (100, 200, 85)
271 rgb_string = '(' + ', '.join([str(el) for el in rgb]) + ')'
272 print(ut.colorize("RGB Tuples like:", style = "bold"), ut.colorize(rgb_string, rgb, "bold"))
274def styles():
275 from plotext._utility import styles, colorize, title_color
276 c = [colorize(el, style = el) for el in styles]
277 c = '\n'.join(c)
278 print(c)
279 mul = 'bold italic dim'
280 print('\n' + colorize('multiple styles are accepted, ', title_color) + 'eg: ' + colorize(mul, style = mul))
282def themes():
283 themes = list(_themes.keys())[::]
284 l = len(themes)
285 rows = int(sqrt(l))
286 cols = ceil(l / rows)
287 y1 = ut.sin(periods = 1)
288 y2 = ut.sin(periods = 1, phase = -1)
289 figure.clf()
290 figure.subplots(rows, cols)
291 for row in range(1, rows + 1):
292 for col in range(1, cols + 1):
293 i = (row - 1) * cols + col - 1
294 if i < l:
295 subplot = figure.subplot(row, col)
296 subplot.theme(themes[i])
297 subplot.title(themes[i])
298 subplot.scatter(y1); subplot.plot(y2)
299 figure.show()
300 figure.clf()
302##############################################
303########### Test Function #############
304##############################################
306def test():
307 import random
308 figure.clf(); figure.clt()
309 figure.date_form("d/m/Y");
310 figure.take_min()
311 figure.plot_size(None, ut.terminal_height())
312 #figure.plot_size(108, 70)
314 figure.plotsize(ut.tw(), ut.th() - 5)
315 figure.subplots(2, 2)
317 subplot = figure.subplot(1, 1)
318 subplot.title("Multiple Axes Plot")
319 subplot.canvas_color(66); subplot.axes_color(4); subplot.ticks_color(216); subplot.ticks_style('bold italic')
320 y = ut.sin(periods = 1); l = len(y)
321 subplot.scatter(y, label = "lower left")
322 x = [figure.today_datetime() + dt.timedelta(days = i) for i in range(l)]; x = figure.datetimes_to_strings(x)
323 subplot.plot(x, x, label = 'upper right - all dates', xside = 2, yside = 2)
324 subplot.vline(l / 2, 'red')
325 subplot.hline(0, 200)
326 subplot.text("origin", l // 2, 0, color = 'red', alignment = 'center')
327 subplot.xlabel('x lower'); subplot.xlabel('x upper', 2)
328 subplot.ylabel('y left', 'left'); subplot.ylabel('y right', 'right')
329 subplot.xfrequency(8); subplot.xfrequency(5, 2);
330 subplot.yfrequency(3); subplot.yfrequency(5, 2);
331 subplot.grid(1,1)
333 subplot = figure.subplot(1, 2)
334 subplot.theme('innocent')
335 xb = ["Sausage", "Pepperoni", "Mushrooms", "Cheese", "Chicken", "Beef"]
336 y1 = [36, 14, 11, 8, 7, 4]
337 y2 = [20, 12, 35, 15, 4, 5]
338 subplot.stacked_bar(xb, [y1, y2], labels = ["men", "women"])
340 subplot = figure.subplot(2, 1)
341 subplot.theme('dreamland')
342 ld = 7 * 10 ** 4
343 data = [random.gauss(0, 1) for el in range(10 * ld)]
344 subplot.hist(data, bins = 60, label="mean 0")
345 subplot.frame(1); #subplot.xaxes(1, 0); subplot.yaxes(1, 0)
347 subplot = figure.subplot(2, 2)
348 subplot.canvas_color('gray+'); subplot.axes_color('gray+')
349 ut.download(test_image_url, 'cat.jpg')
350 subplot.image_plot('cat.jpg', grayscale = False)
351 ut.delete_file('cat.jpg')
352 subplot.title('A very Cute Cat')
353 subplot.frame(0)
355 #figure.plotsize(0, 0)
356 figure.show()
357 figure._get_time()
358 figure.save_fig('test.txt')
359 figure.save_fig('test.html')
360 #figure.clf()