runs.html


001| """Baseball Charts - Season Runs (Scored, Differential, Accumulated, Histograms).
001| 
001| Classes:
001|     parameters (dict)
001| 
001| Functions:
001|     make_chart (plot_function, **params)            ~generate chart
001|     dispatch (cmd, **kwargs)                        ~module dispatch
001| 
001| Commands:
001|     runs        do_runs_scored_chart                ~runs scored per game chart
001|     diff        do_run_diff_chart                   ~run differential chart
001|     wl          do_runs_win_lose_chart              ~runs won/lost by chart
001|     accum       do_runs_accumulated_chart           ~runs accumulated chart
001| 
001|     hist        do_runs_histogram                   ~runs scored per game histogram
001|     hist2       do_runs_win_lose_histogram          ~runs won/lost by chart
001| 
001|     all         do_all                              ~all the charts
001|     test        do_test                             ~test
001| 
001| """

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| import matplotlib.pyplot as plt
007| import matplotlib.ticker as mltick
008| import matplotlib.patches as mlpatch
009| from logger import logger,info,debug,trace
010| from goodies import KWARG, marker
011| import defs
012| ####################################################################################################
013| Log = logger('Runs')
014| 
015| CMND = ''
016| ARGS = {
017|     #'team':'twins',
018|     #'year':'2025',
019|     #'fpath': defs.BasePath,
020| }
021| 
022| 
023| ##------------------------------------------------------------------------------------------------##
024| ScoredRunsColors = ['#3366ff', '#1fbf33', '#cc9933', '#ff0000']
025| 
026| 
027| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
028| class parameters (dict):
029|     """Specialized dictionary for the chart maker.
029| 
029| Required keyword arguments for new instances:
029|     title       ~title
029|     filename    ~filename (path and name)
029|     ymax        ~y-axis maximum
029| 
029| Optional keyword arguments:
029|     width, height
029|     xlabel, ylabel
029|     xmin, xmax, ymin
029|     xtick0, xtick1
029|     ytick0, ytick1
029| 
029| To change parameters with no keyword argument:
029| 
029|     params = parameters(<keyword-params>)
029|     params['margin.left'] = 0.075
029|     params['margin.bottom'] = 0.15
029| 
029| """

030|     def __init__ (self, **kwargs):
031|         """New instance. Create required parameters."""
032| 
033|         self['suptitle'] = kwargs['title']
034|         self['filename'] = kwargs['filename']
035|         self['width']    = KWARG('width' , 10.0, float, kwargs)
036|         self['height']   = KWARG('height',  4.0, float, kwargs)
037| 
038|         self['xlabel'] = KWARG('xlabel', 'Games', str, kwargs)
039|         self['xmin']   = KWARG('xmin',   0.5, float, kwargs)
040|         self['xmax']   = KWARG('xmax', 162.5, float, kwargs)
041|         self['xtick0'] = KWARG('xtick0', 10, int, kwargs)
042|         self['xtick1'] = KWARG('xtick1',  1, int, kwargs)
043|         self['xformat'] = '%d'
044| 
045|         self['ylabel'] = KWARG('ylabel', 'Runs', str, kwargs)
046|         self['ymin']   = KWARG('ymin', 0, int, kwargs)
047|         self['ymax']   = kwargs['ymax']
048|         self['ytick0'] = KWARG('ytick0',100, int, kwargs)
049|         self['ytick1'] = KWARG('ytick1', 20, int, kwargs)
050|         self['yformat'] = '%d'
051| 
052|         self['margin.left']   = 0.065
053|         self['margin.right']  = 0.990
054|         self['margin.bottom'] = 0.150
055|         self['margin.top']    = 0.920
056| 
057| 
058| ##================================================================================================##
059| def create_chart (plot_function, **params):
060|     """Generate the multiple team progress chart."""
061| 
062|     # Get the various required chart parameters...
063|     suptitle = params['suptitle']
064|     filename = params['filename']
065|     width    = params['width']
066|     height   = params['height']
067|     margin_l = params['margin.left']
068|     margin_r = params['margin.right']
069|     margin_b = params['margin.bottom']
070|     margin_t = params['margin.top']
071| 
072|     xlabel = params['xlabel']
073|     xmin   = params['xmin']
074|     xmax   = params['xmax']
075|     xtick0 = params['xtick0']
076|     xtick1 = params['xtick1']
077|     xfmt   = params['xformat']
078| 
079|     ylabel = params['ylabel']
080|     ymin   = params['ymin']
081|     ymax   = params['ymax']
082|     ytick0 = params['ytick0']
083|     ytick1 = params['ytick1']
084|     yfmt   = params['yformat']
085| 
086|     # Create a chart...
087|     fig, ax = plt.subplots()
088| 
089|     fig.set_figwidth(width)
090|     fig.set_figheight(height)
091|     fig.subplots_adjust(left=margin_l, right=margin_r, bottom=margin_b, top=margin_t)
092|     fig.suptitle(suptitle, fontsize=14, fontweight='bold')
093| 
094|     # Configure X-axis...
095|     ax.set_xlabel(xlabel, fontsize=12, fontweight='bold')
096|     ax.set_xlim(xmin, xmax)
097|     ax.xaxis.set_major_locator(mltick.MultipleLocator(xtick0))
098|     ax.xaxis.set_minor_locator(mltick.MultipleLocator(xtick1))
099|     ax.xaxis.set_major_formatter(mltick.FormatStrFormatter(xfmt))
100| 
101|     for tick in ax.xaxis.get_major_ticks():
102|         tick.label1.set_rotation('vertical')
103|         tick.label1.set_size(9)
104| 
105|     # Configure Y-axis...
106|     ax.set_ylabel(ylabel, fontsize=12, fontweight='bold')
107|     ax.set_ylim(ymin, ymax)
108|     ax.yaxis.set_major_locator(mltick.MultipleLocator(ytick0))
109|     ax.yaxis.set_minor_locator(mltick.MultipleLocator(ytick1))
110|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter(yfmt))
111| 
112|     # Configure grid...
113|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
114|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
115|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
116|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
117| 
118|     # Have the callback function plot the data...
119|     plot_function(fig, ax)
120| 
121|     # Save the chart as a PNG file...
122|     fig.savefig(filename)
123|     defs.prn(f'wrote: {filename}')
124|     defs.prn()
125|     return filename
126| 
127| 
128| ##================================================================================================##
129| def do_runs_scored_chart (**kwargs):
130|     """CMND: Create a chart of runs scored in each game."""
131|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
132|     fname = KWARG('fname', '{tcode}-{year}-runs-scored.png', str, kwargs)
133|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
134|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
135|     team_name = defs.MlbTeams[tcode][2]
136|     file_name = path.join(fpath,fname) if fpath else fname
137|     file_name = file_name.format(**locals())
138|     Log.info(f'runs-scored-chart:: {list(kwargs.keys())}')
139|     Log.debug(f'{fpath=}')
140|     Log.debug(f'{fname=}')
141|     Log.debug(f'{tcode=}')
142|     Log.debug(f'{year=}')
143|     Log.debug(f'{team_name=}')
144|     Log.debug(f'{file_name=}')
145|     Log.info()
146| 
147|     def bar_color (runs):
148|         if 10 <= runs: return ScoredRunsColors[0]
149|         if 5 <= runs: return ScoredRunsColors[1]
150|         if 1 < runs: return ScoredRunsColors[2]
151|         return ScoredRunsColors[3]
152| 
153|     # Extract data from Twins season...
154|     csv_data = defs.CsvTeamGames(tcode)
155|     runs_scored = csv_data.get_column_data_int('R')
156| 
157|     # Process data for chart...
158|     xs = []
159|     ys = []
160|     cs = []
161|     for rx,rs in enumerate(runs_scored, start=1):
162|         xs.append(rx)
163|         ys.append(rs)
164|         cs.append(bar_color(rs))
165| 
166|     ymax = defs.RoundUp(max(ys), 10)
167| 
168|     # Chart setup...
169|     def plot_function (fig, ax):
170|         # Plot data...
171|         ax.bar(xs,ys, width=1.00, color=cs, alpha=0.95, zorder=11)
172| 
173|         # Create legend...
174|         patchs = [
175|             mlpatch.Patch(facecolor=ScoredRunsColors[0], edgecolor='#000000', lw=0.75),
176|             mlpatch.Patch(facecolor=ScoredRunsColors[1], edgecolor='#000000', lw=0.75),
177|             mlpatch.Patch(facecolor=ScoredRunsColors[2], edgecolor='#000000', lw=0.75),
178|             mlpatch.Patch(facecolor=ScoredRunsColors[3], edgecolor='#000000', lw=0.75),
179|         ]
180|         labels = ['10+ runs', '5-9 runs', '2-4 runs', '1 run']
181|         ax.legend(patchs, labels, loc='upper right', ncols=5, fontsize=10, bbox_to_anchor=(1.005,1.018))
182| 
183|     params = parameters(
184|         title = f'{team_name} {year} Runs Scored'.format(**locals()),
185|         filename = file_name,
186|         ymax = ymax,
187|         ytick0 = 5,
188|         ytick1 = 1,
189|     )
190|     params['margin.left'] = 0.055
191| 
192|     # Create (and return) chart...
193|     return create_chart(plot_function, **params)
194| 
195| ##================================================================================================##
196| def do_run_diff_chart (**kwargs):
197|     """CMND: Create a Run Differential Chart."""
198|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
199|     fname = KWARG('fname', '{tcode}-{year}-run-diff.png', str, kwargs)
200|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
201|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
202|     team_name = defs.MlbTeams[tcode][2]
203|     file_name = path.join(fpath,fname) if fpath else fname
204|     file_name = file_name.format(**locals())
205|     Log.info(f'run-diff-chart:: {list(kwargs.keys())}')
206|     Log.debug(f'{fpath=}')
207|     Log.debug(f'{fname=}')
208|     Log.debug(f'{tcode=}')
209|     Log.debug(f'{year=}')
210|     Log.debug(f'{team_name=}')
211|     Log.debug(f'{file_name=}')
212|     Log.info()
213| 
214|     # Extract data from team's season...
215|     csv_data = defs.CsvTeamGames(tcode)
216|     runs_scored = csv_data.get_column_data_int('R')
217|     runs_allowed = csv_data.get_column_data_int('RA')
218| 
219|     # Process data for chart...
220|     xs = []
221|     ys = []
222|     cs = []
223|     run_diff = 0
224|     for rx,rs,ra in zip(marker(1), runs_scored, runs_allowed):
225|         run_diff += (rs - ra)
226|         xs.append(rx)
227|         ys.append(run_diff)
228|         cs.append('#ff0000' if run_diff < 0 else ('#00cc00' if 0 < run_diff else '#0000ff'))
229| 
230|     ymax = defs.RoundUp(max(ys), 20)
231|     ymin = defs.RoundDown(min(ys), 20)
232| 
233|     # Chart setup...
234|     def plot_function (fig, ax):
235|         # Plot data...
236|         ax.axhline(0.0, lw=1.7, color='#000000', alpha=0.75, zorder=10)
237|         ax.bar(xs,ys, width=1.00, color=cs, alpha=0.95, zorder=11)
238| 
239|     params = parameters(
240|         title = f'{team_name} {year} Run Differential'.format(**locals()),
241|         filename = file_name,
242|         ymin = ymin,
243|         ymax = ymax,
244|         ytick0 = 20,
245|         ytick1 =  5,
246|     )
247|     params['yformat'] = '%+d'
248| 
249|     # Create (and return) chart...
250|     return create_chart(plot_function, **params)
251| 
252| ##================================================================================================##
253| def do_runs_win_lose_chart (**kwargs):
254|     """CMND: Create a Runs Won/Lost By Chart."""
255|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
256|     fname = KWARG('fname', '{tcode}-{year}-runs-won-lost.png', str, kwargs)
257|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
258|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
259|     team_name = defs.MlbTeams[tcode][2]
260|     file_name = path.join(fpath,fname) if fpath else fname
261|     file_name = file_name.format(**locals())
262|     Log.info(f'runs-won-lost-by-chart:: {list(kwargs.keys())}')
263|     Log.debug(f'{fpath=}')
264|     Log.debug(f'{fname=}')
265|     Log.debug(f'{tcode=}')
266|     Log.debug(f'{year=}')
267|     Log.debug(f'{team_name=}')
268|     Log.debug(f'{file_name=}')
269|     Log.info()
270| 
271|     # Extract data from team's season...
272|     csv_data = defs.CsvTeamGames(tcode)
273|     runs_scored = csv_data.get_column_data_int('R')
274|     runs_allowed = csv_data.get_column_data_int('RA')
275| 
276|     # Process data for chart...
277|     xs = []
278|     ys = []
279|     cs = []
280|     for rx,rs,ra in zip(marker(1), runs_scored, runs_allowed):
281|         dif = (rs - ra)
282|         xs.append(rx)
283|         ys.append(dif)
284|         cs.append('#ff0000' if dif < 0 else ('#00cc00' if 0 < dif else '#0000ff'))
285| 
286|     ymax = defs.RoundUp(max(ys), 10)
287|     ymin = defs.RoundDown(min(ys), 10)
288| 
289|     # Chart setup...
290|     def plot_function (fig, ax):
291|         # Plot data...
292|         ax.axhline(0, lw=1.7, color='#000000', alpha=0.75, zorder=10)
293|         ax.bar(xs,ys, width=1.00, color=cs, alpha=0.95, zorder=11)
294| 
295|     params = parameters(
296|         title = f'{team_name} {year} Runs Won/Lost By'.format(**locals()),
297|         filename = file_name,
298|         ymin = ymin,
299|         ymax = ymax,
300|         ytick0 = 10,
301|         ytick1 =  2,
302|     )
303|     params['yformat'] = '%+d'
304| 
305|     # Create (and return) chart...
306|     return create_chart(plot_function, **params)
307| 
308| ##================================================================================================##
309| def do_runs_accumulated_chart (**kwargs):
310|     """CMND: Create a chart of runs accumlated over the season."""
311|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
312|     fname = KWARG('fname', '{tcode}-{year}-runs-accum.png', str, kwargs)
313|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
314|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
315|     team_name = defs.MlbTeams[tcode][2]
316|     file_name = path.join(fpath,fname) if fpath else fname
317|     file_name = file_name.format(**locals())
318|     Log.info(f'runs-accumulated-chart:: {list(kwargs.keys())}')
319|     Log.debug(f'{fpath=}')
320|     Log.debug(f'{fname=}')
321|     Log.debug(f'{tcode=}')
322|     Log.debug(f'{year=}')
323|     Log.debug(f'{team_name=}')
324|     Log.debug(f'{file_name=}')
325|     Log.info()
326| 
327|     # Extract data from team's season...
328|     csv_data = defs.CsvTeamGames(tcode)
329|     runs_scored = csv_data.get_column_data_int('R')
330|     runs_allowed = csv_data.get_column_data_int('RA')
331| 
332|     # Process data for chart...
333|     xs = []
334|     ys1 = []
335|     ys2 = []
336|     rs_total = 0
337|     ra_total = 0
338|     for rx,rs,ra in zip(marker(1), runs_scored, runs_allowed):
339|         rs_total += rs
340|         ra_total += ra
341|         xs.append(rx)
342|         ys1.append(rs_total)
343|         ys2.append(ra_total)
344| 
345|     ymax = defs.RoundUp(max(ys1+ys2), 100)
346| 
347|     # Chart setup...
348|     def plot_function (fig, ax):
349|         # Plot data...
350|         ax.plot(xs,ys1, c='#0000ff', lw=2.5, alpha=0.8, zorder=12)
351|         ax.plot(xs,ys2, c='#ff0000', lw=2.5, alpha=0.8, zorder=11)
352| 
353|         # Create legend...
354|         patchs = [
355|             mlpatch.Patch(facecolor='#0000ff', edgecolor='#000000', lw=0.75),
356|             mlpatch.Patch(facecolor='#ff0000', edgecolor='#000000', lw=0.75),
357|         ]
358|         labels = [team_name, 'Opponents']
359|         ax.legend(patchs, labels, loc='upper left', ncols=1, fontsize=12, bbox_to_anchor=(0.000,1.010))
360| 
361|     params = parameters(
362|         title = f'{team_name} {year} Runs Accumulated'.format(**locals()),
363|         filename = file_name,
364|         height = 6.0,
365|         ymax = ymax,
366|     )
367|     params['margin.bottom'] = 0.100
368|     params['margin.top']    = 0.940
369| 
370|     # Create (and return) chart...
371|     return create_chart(plot_function, **params)
372| 
373| ##================================================================================================##
374| def do_runs_histogram (**kwargs):
375|     """CMND: Create a Runs Scored/Game Histogram."""
376|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
377|     fname = KWARG('fname', '{tcode}-{year}-runs-histogram.png', str, kwargs)
378|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
379|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
380|     team_name = defs.MlbTeams[tcode][2]
381|     file_name = path.join(fpath,fname) if fpath else fname
382|     file_name = file_name.format(**locals())
383|     chart_title = f'{team_name} {year} Runs Histogram'.format(**locals())
384|     Log.info(f'runs-scored-per-game-histogram:: {list(kwargs.keys())}')
385|     Log.debug(f'{fpath=}')
386|     Log.debug(f'{fname=}')
387|     Log.debug(f'{tcode=}')
388|     Log.debug(f'{year=}')
389|     Log.debug(f'{file_name=}')
390|     Log.debug(f'{team_name=}')
391|     Log.debug(f'{chart_title=}')
392|     Log.info()
393| 
394|     # Extract data from Twins season...
395|     csv_data = defs.CsvTeamGames(team_name)
396|     runs_scored = csv_data.get_column_data_int('R')
397|     runs_allowed = csv_data.get_column_data_int('RA')
398| 
399|     # Process data for chart...
400|     team_runs = {} # histogram bins
401|     opps_runs = {}
402| 
403|     for rs,ra in zip(runs_scored, runs_allowed):
404| 
405|         if rs not in team_runs: team_runs[rs] = 0
406|         team_runs[rs] += 1
407| 
408|         if ra not in opps_runs: opps_runs[ra] = 0
409|         opps_runs[ra] += 1
410| 
411|     xs = list(range(len(csv_data)))
412|     ys1 = [team_runs[x] if x in team_runs else 0 for x in xs]
413|     ys2 = [opps_runs[x] if x in opps_runs else 0 for x in xs]
414| 
415|     xmax = max(*list(team_runs.keys()), *list(opps_runs.keys()))
416|     vals = (*list(team_runs.values()), *list(opps_runs.values()))
417|     ymax = defs.RoundUp(max(vals), 10)
418|     Log.debug(f'{xmax=}, {ymax=}')
419|     Log.debug()
420| 
421|     # Create a chart...
422|     fig, ax = plt.subplots()
423| 
424|     fig.set_figwidth(10.0)
425|     fig.set_figheight(4.0)
426|     fig.subplots_adjust(left=0.060, right=0.990, bottom=0.135, top=0.920)
427|     fig.suptitle(chart_title, fontsize=14, fontweight='bold')
428| 
429|     # Configure X-axis...
430|     ax.set_xlabel('Number of Runs Scored in Game', fontsize=12, fontweight='bold')
431|     ax.set_xlim(-0.5, xmax+0.5)
432|     ax.xaxis.set_major_locator(mltick.MultipleLocator(1))
433|     ax.xaxis.set_minor_locator(mltick.NullLocator())
434|     ax.xaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
435| 
436|     # Configure Y-axis...
437|     ax.set_ylabel('Number of Times', fontsize=12, fontweight='bold')
438|     ax.set_ylim(0, ymax)
439|     ax.yaxis.set_major_locator(mltick.MultipleLocator(5))
440|     ax.yaxis.set_minor_locator(mltick.MultipleLocator(1))
441|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
442| 
443|     # Configure grid...
444|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
445|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
446|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
447|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
448| 
449|     # Plot data...
450|     props = dict(align='edge', edgecolor='#000000', lw=0.75, alpha=0.95)
451|     ax.bar(xs,ys1, width=-0.40, color=defs.TwinsBlue, zorder=12, **props)
452|     ax.bar(xs,ys2, width=+0.40, color=defs.Opponents, zorder=11, **props)
453| 
454|     # Create legend...
455|     patchs = [
456|         mlpatch.Patch(facecolor=defs.TwinsBlue, edgecolor='#000000', lw=0.75),
457|         mlpatch.Patch(facecolor=defs.Opponents, edgecolor='#000000', lw=0.75),
458|     ]
459|     labels = [team_name, 'Opponents']
460|     ax.legend(patchs, labels, loc='upper right', ncols=2, fontsize=12, bbox_to_anchor=(1.005,1.018))
461| 
462|     # Save the chart...
463|     fig.savefig(file_name)
464|     defs.prn(f'wrote: {file_name}')
465|     defs.prn()
466|     return file_name
467| 
468| ##================================================================================================##
469| def do_runs_win_lose_histogram (**kwargs):
470|     """CMND: Create a game runs win/lost histogram."""
471|     fpath = KWARG('fpath', defs.HtmlPath, str, kwargs)
472|     fname = KWARG('fname', '{tcode}-{year}-won-lost-runs-histo.png', str, kwargs)
473|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
474|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
475|     team_name = defs.MlbTeams[tcode][2]
476|     file_name = path.join(fpath,fname) if fpath else fname
477|     file_name = file_name.format(**locals())
478|     chart_title = f'{team_name} {year} Won/Lost Runs Histogram'.format(**locals())
479|     Log.info(f'won-lost-runs-histogram:: {list(kwargs.keys())}')
480|     Log.debug(f'{fpath=}')
481|     Log.debug(f'{fname=}')
482|     Log.debug(f'{tcode=}')
483|     Log.debug(f'{year=}')
484|     Log.debug(f'{team_name=}')
485|     Log.debug(f'{file_name=}')
486|     Log.info()
487| 
488|     # Extract data from team's season...
489|     csv_data = defs.CsvTeamGames(tcode)
490|     runs_scored  = csv_data.get_column_data_int('R')
491|     runs_allowed = csv_data.get_column_data_int('RA')
492| 
493|     data_bins = {}
494|     for rs,ra in zip(runs_scored, runs_allowed):
495|         dif = rs - ra
496|         if dif not in data_bins: data_bins[dif] = 0
497|         data_bins[dif] += 1
498| 
499|     # Find highest key and generate X-axis ticks...
500|     xmax = max(abs(key) for key in data_bins)
501|     xs = list(range(1, xmax+1))
502| 
503|     # Process the data...
504|     ys1 = []
505|     ys2 = []
506|     for x in xs:
507|         # Won...
508|         if x in data_bins:
509|             ys1.append(data_bins[x])
510|         else:
511|             ys1.append(0)
512| 
513|         # Lost...
514|         if -x in data_bins:
515|             ys2.append(data_bins[-x])
516|         else:
517|             ys2.append(0)
518| 
519|     ymax = defs.RoundUp(max(ys1+ys2), 10)
520| 
521|     for x,y1,y2 in zip(xs, ys1, ys2):
522|         Log.trace(f'{x}: {y1} {y2}')
523|     Log.trace()
524| 
525|     # Create a chart...
526|     fig, ax = plt.subplots()
527| 
528|     fig.set_figwidth(10.0)
529|     fig.set_figheight(4.0)
530|     fig.subplots_adjust(left=0.060, right=0.990, bottom=0.135, top=0.920)
531|     fig.suptitle(chart_title, fontsize=14, fontweight='bold')
532| 
533|     # Configure X-axis...
534|     ax.set_xlabel('Number of Runs Games Won/Lost By', fontsize=12, fontweight='bold')
535|     ax.set_xlim(0.5, xmax+0.5)
536|     ax.xaxis.set_major_locator(mltick.MultipleLocator(1))
537|     ax.xaxis.set_minor_locator(mltick.NullLocator())
538|     ax.xaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
539| 
540|     # Configure Y-axis...
541|     ax.set_ylabel('Number of Times', fontsize=12, fontweight='bold')
542|     ax.set_ylim(0, ymax)
543|     ax.yaxis.set_major_locator(mltick.MultipleLocator(5))
544|     ax.yaxis.set_minor_locator(mltick.MultipleLocator(1))
545|     ax.yaxis.set_major_formatter(mltick.FormatStrFormatter('%d'))
546| 
547|     # Configure grid...
548|     ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
549|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
550|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
551|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
552| 
553|     # Plot data...
554|     props = dict(align='edge', edgecolor='#000000', lw=0.75, alpha=0.95)
555|     ax.bar(xs,ys1, width=-0.40, color=defs.TwinsBlue, zorder=12, **props)
556|     ax.bar(xs,ys2, width=+0.40, color=defs.Opponents, zorder=11, **props)
557| 
558|     # Create legend...
559|     patchs = [
560|         mlpatch.Patch(facecolor=defs.TwinsBlue, edgecolor='#000000', lw=0.75),
561|         mlpatch.Patch(facecolor=defs.Opponents, edgecolor='#000000', lw=0.75),
562|     ]
563|     labels = [team_name, 'Opponents']
564|     ax.legend(patchs, labels, loc='upper right', ncols=2, fontsize=12, bbox_to_anchor=(1.005,1.018))
565| 
566|     # Save the chart...
567|     fig.savefig(file_name)
568|     defs.prn(f'wrote: {file_name}')
569|     defs.prn()
570|     return file_name
571| 
572| ##================================================================================================##
573| def do_all (**kwargs):
574|     '''Do all charts.'''
575|     Log.info(f'do-all:: {list(kwargs.keys())}')
576|     Log.info()
577| 
578|     rvs = []
579| 
580|     rvs.append(do_runs_scored_chart(**kwargs))
581|     rvs.append(do_run_diff_chart(**kwargs))
582|     rvs.append(do_runs_win_lose_chart(**kwargs))
583|     rvs.append(do_runs_accumulated_chart(**kwargs))
584| 
585|     rvs.append(do_runs_histogram(**kwargs))
586|     rvs.append(do_runs_win_lose_histogram(**kwargs))
587| 
588|     return rvs
589| 
590| ##================================================================================================##
591| def do_test (**kwargs):
592|     """CMND: Do a test."""
593|     fpath = KWARG('fpath', defs.BasePath, str, kwargs)
594|     fname = KWARG('fname', 'test-{tcode}-{year}.png', str, kwargs)
595|     tcode = KWARG('team', defs.TwinsCode, str, kwargs)
596|     year  = KWARG('year', defs.DefaultYear, int, kwargs)
597|     team_name = defs.MlbTeams[tcode][2]
598|     file_name = path.join(fpath,fname) if fpath else fname
599|     file_name = file_name.format(**locals())
600|     Log.info(f'test:: {list(kwargs.keys())}')
601|     Log.debug(f'{fpath=}')
602|     Log.debug(f'{fname=}')
603|     Log.debug(f'{tcode=}')
604|     Log.debug(f'{year=}')
605|     Log.debug(f'{team_name=}')
606|     Log.debug(f'{file_name=}')
607|     Log.info()
608| 
609|     # Extract data from team's season...
610|     csv_data = defs.CsvTeamGames(tcode)
611| 
612|     Log.info()
613|     return file_name
614| 
615| ####################################################################################################
616| def dispatch (cmd, **kwargs):
617|     """Dispatch to a module function based on CMD."""
618|     Log.info(f'CMD: {cmd}')
619|     for kw in kwargs:
620|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
621|     Log.info()
622| 
623|     if cmd == 'runs':  return do_runs_scored_chart          (**kwargs)
624|     if cmd == 'diff':  return do_run_diff_chart             (**kwargs)
625|     if cmd == 'wl':    return do_runs_win_lose_chart        (**kwargs)
626|     if cmd == 'accum': return do_runs_accumulated_chart     (**kwargs)
627|     if cmd == 'hist':  return do_runs_histogram             (**kwargs)
628|     if cmd == 'hist2': return do_runs_win_lose_histogram    (**kwargs)
629|     if cmd == 'all':   return do_all                        (**kwargs)
630|     if cmd == 'test':  return do_test                       (**kwargs)
631| 
632|     return 'Nothing to do!'
633| ####################################################################################################
634| if __name__ == '__main__':
635|     print(f'autorun: {argv[0]}')
636|     Log.start(path.join(defs.BasePath,'runs.log'))
637|     Log.level(trace())
638|     Log.info(argv[0])
639|     cmd = argv[1] if 1 < len(argv) else CMND
640|     kwargs = ARGS
641|     for a in argv[2:]:
642|         nv = a.split('=', 1)
643|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
644|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
645|     Log.info()
646|     try:
647|         print(f'CMD: {cmd}')
648|         print()
649|         obj = dispatch(cmd, **kwargs)
650|         print(obj)
651|         print()
652|         Log.info(obj)
653|         Log.info()
654|     except:
655|         etype, evalue, tb = exc_info()
656|         ts = extract_tb(tb)
657|         Log.error()
658|         Log.error(f'{etype.__name__}: {evalue!s}')
659|         Log.error()
660|         for t in ts[-5:]:
661|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
662|             Log.error(f' {t[3]}')
663|             Log.error()
664|         raise
665|     finally:
666|         Log.end()
667| ####################################################################################################
668| """eof"""
669|