def age_dist_animation( variable, show_population, lang, window, normalize, interpolation, save, overwrite, out_dir, filename_fmt, fps, dpi, hold_last_frame, figsize, interval, repeat, repeat_delay, ): ic.set_locale(lang) data = ic.fix_monotonicity(ic.get())[['cases', 'deaths']] plt.Figure(figsize=figsize) chart = ic.charts.AgeDistributionBarChart( data, variable=variable, normalize=normalize, window=window, population_distribution=(ic.get_population_by_age_group().percentage if show_population else None), resample_kwargs=dict(method=interpolation)) animation = chart.animation( interval=interval, repeat=repeat, repeat_delay= repeat_delay, # FIXME: repeat_delay doesn't work, not sure why ) if not save: plt.show() return 0 # Create the folder(s) if they don't exist out_dir = Path(out_dir) out_dir.mkdir(exist_ok=True, parents=True) # Compute the output path if filename_fmt is None: title = plt.gca().get_title().lower() filename = to_filename(title).capitalize() else: filename = filename_fmt.format(window=window) out_path = (out_dir / filename).with_suffix('.mp4') if out_path.exists(): if overwrite: print('Removing file', out_path, '...') out_path.unlink() else: print(f'The file {out_path} already exists. ' f'Pass -o/--overwrite to overwrite it.') return 1 # Save the animation to a file with a random name first tmp_path = out_dir / (rand_string(16) + out_path.suffix) writer = FFMpegWriter(fps=fps, metadata=dict(artist='Me')) progress_bar = tqdm(desc='Saving the video', total=animation.save_count, unit='frame') animation.save( str(tmp_path), writer=writer, dpi=dpi, progress_callback=lambda *_: progress_bar.update(), ) progress_bar.close() print('\n') if hold_last_frame: print( f'Running FFMpeg to hold the last frame for {hold_last_frame:.1f} seconds:\n' ) pretty_command = dedent(f''' ffmpeg -y -i {tmp_path} -vf tpad=stop_mode=clone:stop_duration={hold_last_frame} {out_path} ''') print(pretty_command, flush=True) command_tokens = pretty_command.split() result = subprocess.run(command_tokens, capture_output=True) tmp_path.unlink() # remove the temp file if result.returncode != 0: print('FFMpeg error:\n', result.stderr.decode('utf-8')) return 1 else: # Just rename the temp file tmp_path.rename(out_path) print(f'Video saved to {out_path}')
else: ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:n}')) if ylim: ax.set_ylim(0, ylim * ax.get_ylim()[1]) # Title base_title = strings[f'{variable}_age_distribution' if normalize else f'average_daily_{variable}'] if freq == 'M': period_label = strings['month_by_month'] elif freq in {'W', 'W-SUN'}: period_label = strings['week_by_week'] elif isinstance(freq, int): period_label = strings.get('by_periods_of_n_days', count=freq) title = f"{base_title} {period_label}" ax.set_title(title) return ax if __name__ == '__main__': plt.style.use('seaborn') ic.set_locale('it') df = ic.fix_monotonicity(ic.get()) anim = AgeDistributionBarChart( df, window=1, population_distribution=ic.get_population_by_age_group( ).percentage).animation() plt.show()
check_age_group_size(age_group_size) period_slice = slice(*period) if period else slice(data.index[0], None) r = resample_if_needed(data[variable].drop(columns="unknown"), "D") d = r[period_slice] d = d.diff(window).iloc[window:] d = ic.aggregate_age_groups(d, cuts=age_group_size, fmt_last="{}+") if window > 1: d = d / window figure_args.setdefault("figsize", DOUBLE_CHART_FIGSIZE) fig, ax = plt.subplots(2, 1, **figure_args) area_chart(d, ax=ax[0], lang=strings.lang) area_chart(d, ax=ax[1], normalize=True, lang=strings.lang) ax[0].set_title( strings.get(f"running_average_{variable}_title", count=window)) return fig if __name__ == "__main__": plt.style.use('seaborn') resampled = ic.resample(ic.get()[["cases"]]) iccas.i18n.set_language('en') double_area_chart_of_running_averages(resampled, window=14) plt.show() iccas.i18n.set_language('it') double_area_chart_of_running_averages(resampled, window=14) plt.show()
def _data(tmpdir_factory): cache_dir = tmpdir_factory.mktemp("data") return iccas.get(cache_dir=cache_dir).head(10)
def test_get(tmp_path: Path): d = iccas.get(cache_dir=tmp_path) assert isinstance(d, pd.DataFrame) assert isinstance(d.index, pd.DatetimeIndex)