def plot_predicted(values, first_date, save_to: str): labels = ["Хворіють", "Померли", "Одужали"] colors = ["r", "b", "g"] today = arrow.utcnow() x_ticks = np.array([first_date.shift(days=i).datetime for i in range(len(values))]) cum_values = np.cumsum(values, axis=0) fig, axes = plt.subplots(1, 2, figsize=(12, 4)) x_lines = [] x_cum_lines = [] for label, color, arr, cum_arr in zip(labels, colors, values.T, cum_values.T): mask_pred = np.ma.masked_where(x_ticks <= today, arr) mask_real = np.ma.masked_where(x_ticks > today, arr) mask_cum_pred = np.ma.masked_where(x_ticks <= today, cum_arr) mask_cum_real = np.ma.masked_where(x_ticks > today, cum_arr) x_real, x_pred = axes[0].plot(x_ticks, mask_real, f"{color}", x_ticks, mask_pred, f"{color}--") x_real_cum, x_pred_cum = axes[1].plot(x_ticks, mask_cum_real, f"{color}", x_ticks, mask_cum_pred, f"{color}--") x_lines.append((x_real, x_pred)) x_cum_lines.append((x_real_cum, x_pred_cum)) axes[0].legend(x_lines, labels, handler_map={tuple: HandlerTuple(2)}) axes[1].legend(x_cum_lines, labels, handler_map={tuple: HandlerTuple(2)}) fig.autofmt_xdate() plt.savefig(save_to) plt.show()
def test_multiple_keys(): # test legend entries with multiple keys fig, ax = plt.subplots() p1, = ax.plot([1, 2, 3], '-o') p2, = ax.plot([2, 3, 4], '-x') p3, = ax.plot([3, 4, 5], '-d') ax.legend([(p1, p2), (p2, p1), p3], ['two keys', 'pad=0', 'one key'], numpoints=1, handler_map={(p1, p2): HandlerTuple(ndivide=None), (p2, p1): HandlerTuple(ndivide=None, pad=0)})
def setLegend(): legend = [] for entry in data.legend: entrytuple = [] for icon in entry['icons']: (iconColor, iconEdgeColor, iconStyle) = (icon[0], icon[1], icon[2]) if iconStyle in {'o', 'x', '^', '*'}: entrytuple.append( mlines.Line2D([], [], color=iconColor, marker=iconStyle, linestyle='None', markersize=10, markeredgewidth=0.5, markeredgecolor=iconEdgeColor)) else: entrytuple.append( patches.Patch(facecolor=iconColor, edgecolor=iconStyle)) legend.append(tuple(entrytuple)) plt.legend(legend, [entry['label'] for entry in data.legend], numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}, loc='upper right') plt.title(data.chartName, fontsize=16) plt.gcf().canvas.set_window_title(data.windowName)
def plot_figure(tran_metric, val_metric, metric_type='Loss'): c = [ 'red', 'brown', 'orange', 'darkmagenta', 'gold', 'coral', 'lightgreen', 'slategray', 'pink', 'tan', 'darkkhaki', 'greenyellow', 'gray', 'lime', 'blue', 'indigo' ] models = [ 'NoPr/simple', 'NoPr/batch', 'NoPr/bayes', 'NoPr/bayes+batch', 'STD/simple', 'STD/batch', 'STD/bayes', 'STD/bayes+batch', 'ZCA/simple', 'ZCA/batch', 'ZCA/bayes', 'ZCA/bayes+bacth', 'HE/simple', 'HE/batch', 'HE/bayes', 'HE/bayes+batch' ] plt.figure(figsize=(30, 20)) plot_train = [] plot_val = [] for i in range(16): plot_train.append( plt.plot(tran_metric[i], '-^', color=c[i], markersize=12)) plot_val.append( plt.plot(val_metric[i], '--*', color=c[i], markersize=12)) plt.legend([(plot_train[i][0], plot_val[i][0]) for i in range(16)], models, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}, fontsize=24) plt.xlabel(r'$\# \, of \, epochs$', fontsize=24) plt.ylabel(r'${}$'.format(metric_type), fontsize=24) plt.show()
def make_legend(ax): ax.legend([(p[1], p[2], p[3]), (p[0], p[5], p[6], p[7]), (p[4], p[8])], ['CLO top 3', 'Lit-inspired', 'Other'], numpoints=1, handlelength=2.5, frameon=False, handler_map={tuple: HandlerTuple(ndivide=None)})
def main(): args = parser.parse_args() N = args.num_elements # number of finite elements xmin = .0 # left boundary L = 1.0 # right boundary psi_0 = .0 # left Dirichlet bc psi_L = .0 # right Dirichlet bc x = np.linspace(xmin, L, N + 1) _x = np.linspace(xmin, L, 1000) principal_quantum_numbers = [1, 2, 3] nonreletivistic_energies = [] for n in principal_quantum_numbers: E = n**2 * h**2 / (8 * m_e * L) nonreletivistic_energies.append(E) E, psi, pdf = fem(N, xmin, L, (psi_0, psi_L)) fig, axs = plt.subplots(len(principal_quantum_numbers), 1, sharex='all', figsize=(7, 9)) for i, (n, E) in enumerate( zip(principal_quantum_numbers, nonreletivistic_energies)): psi_analytic = psi_close_form(x, n, L) pdf_analytic = pdf_close_form(x, n, L) l1, = axs[i].plot(_x, psi_close_form(_x, n, L), 'b-') l2, = axs[i].plot(_x, pdf_close_form(_x, n, L), 'r-') if i == 0: # stupid hack, should be fixed l3, = axs[i].plot(x, -psi[:, i], 'bo', markersize=5, alpha=0.8) else: l3, = axs[i].plot(x, psi[:, i], 'bo', markersize=5, alpha=0.8) l4, = axs[i].plot(x, pdf[:, i], 'ro', markersize=5, alpha=0.8) axs[i].legend([l1, l2, (l3, l4)], [r'$\psi(x)$', r'$|\psi(x)|^2$', 'FEM'], handler_map={tuple: HandlerTuple(ndivide=None)}) axs[i].set_title( f'RMSE = {np.round(rmse(pdf_analytic, pdf[:, i]), 5)}') axs[i].legend([l1, l2, (l3, l4)], [r'$\psi(x)$', r'$|\psi(x)|^2$', 'FEM'], handler_map={tuple: HandlerTuple(ndivide=None)}) plt.xlabel(r'$x$') plt.tight_layout() plt.show()
def plot2D_overlay(data_list, labels_list, alpha_list, title): x_min, x_max = np.array((1e9, 1e9)), np.array((-1e9, -1e9)) for data in data_list: x_min = np.minimum(x_min, np.min(data, axis=0)) x_max = np.maximum(x_max, np.max(data, axis=0)) for i in range(len(data_list)): data_list[i] = (data_list[i] - x_min) / (x_max - x_min) fig, ax = plt.subplots(figsize=(8, 8)) cjet = cm.get_cmap("jet") indices_list = [] distinct_labels = [] for labels in labels_list: _, cur_labels, indices = distinct_labels_and_indices(labels) indices_list.append(indices) for label in cur_labels: if label not in distinct_labels: distinct_labels.append(label) num_labels = len(distinct_labels) for i, label in enumerate(distinct_labels): res = 0.0 for data, labels, indices, alpha in zip(data_list, labels_list, indices_list, alpha_list): if label in indices.keys(): index = indices[label] else: index = np.array([]) c = cjet((1.0 * i + res) / (num_labels + 1)) ax.scatter(data[index, 0], data[index, 1], label=label, c=[c], alpha=alpha, linewidths=0.) res += 0.3 handles, labels = ax.get_legend_handles_labels() paired_handles = [] handles_tot = len(handles) // 2 for i in range(handles_tot): paired_handles.append((handles[i * 2], handles[i * 2 + 1])) ax.legend(handles=paired_handles, labels=distinct_labels, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}, loc="center left", bbox_to_anchor=(1, 0, 1, 1), title=title.split('/')[-1]) fig.tight_layout() tikzplotlib.save("%s.tex" % title, figure=fig, strict=True) plt.savefig("%s.png" % title) return fig
def bar_compare(budget_compare_dict): # Check type, if type wrong, return blank plot. if (not (isinstance(budget_compare_dict, (dict, OrderedDict)))): fig, ax = plt.subplots() return fig, ax # Takes a dictionary of dictionaries, budget_compare_dict # First level is budget line items, second is 'expected' and 'actual'. labels = list(budget_compare_dict.keys()) expected_values = [] actual_values = [] for i in range(len(labels)): expected_values.append(budget_compare_dict[labels[i]]['expected']) actual_values.append(budget_compare_dict[labels[i]]['actual']) index = list(range(len(labels))) #print('{}'.format(index)) width = 0.35 width_list = [width] * len(labels) #print('{}'.format(width_list)) ipw = [x + width for x in index] #print('{}'.format(ipw)) ipwd2 = [x + width / 2 for x in index] # Make bar chart fig = plt.figure() ax = fig.add_subplot(111) expected_bars = ax.bar(index, expected_values, width, color='royalblue', edgecolor='k') actual_bars = ax.bar(ipw, actual_values, width) # Set actual bar colours for i in range(len(actual_bars)): if actual_values[i] > expected_values[i]: actual_bars[i].set_color('r') else: actual_bars[i].set_color('g') actual_bars[i].set_edgecolor('k') ax.set_ylabel('Amount ($)') ax.set_xlabel('Category') ax.set_xticks(ipwd2) ax.set_xticklabels(labels, rotation=45) expected_legend_entry = Patch(facecolor='royalblue', edgecolor='k') actual_legend_entry = (Patch(facecolor='g', edgecolor='k'), Patch(facecolor='r', edgecolor='k')) ax.legend([expected_legend_entry, (actual_legend_entry)], ['Expected', 'Actual'], handler_map={tuple: HandlerTuple(ndivide=None)}) plt.tight_layout() # Return graph objects return fig, ax
def legend_tweaks(g, labels, title=None, placement='lower right'): assert len(labels) == 3 handles, _ = g.get_legend_handles_labels() patchList = [[handles[0]], [handles[1]], [handles[2], handles[3]]] g.legend(handles=patchList, labels=labels, handler_map={list: HandlerTuple(None)}, title=title, loc=placement)
def generate_sup_plots_2x2(results_dict, fields=("cutoffs", "scores"), title=None): """Generates plots for the Supplementary Materials that need to be in a 2x2 grid. """ fig, ax = plt.subplots(nrows=2, ncols=2, sharex="col", sharey="row", dpi=200, figsize=(16, 10)) params = [ [{ "metric": "tse_ew", "exp": "bert-large-cased", "title": "BERT cased" }, { "metric": "tse_ew", "exp": "gpt2-xl", "title": "GPT2" }], [{ "metric": "tse_ew", "exp": "bert-large-uncased", "title": "BERT uncased" }, { "metric": "tse_ew", "exp": "roberta-large", "title": "RoBERTa" }], ] for x, y in np.ndindex(ax.shape): kwargs = {} if x == ax.shape[0] - 1: kwargs['display_bottom_ax'] = True elif x == 0: kwargs['display_top_ax'] = True if y == 0: kwargs['display_y_ax'] = True _, _, legend_info = top_bottom_plot_helper(results_dict, ax[x, y], fields=fields, ml=False, legend=False, **params[x][y], **kwargs) legend_labels_sorted, template_names_sorted = legend_info ax[-1, -1].legend(legend_labels_sorted, template_names_sorted, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}, bbox_to_anchor=(0.2, -0.2)) if title: fig.suptitle(title, fontsize=16, fontweight="bold") return fig
def plot_tsne(features, labels, n_sample): colors = ['#440154', '#481567', '#238A8D', '#1F968B', '#DCE319', '#FDE725'] symbols = 'P', 'X', 'o', 'p', 'v', '^' X = np.array(list(chain(*features))) markers = [[symbols[i]] * n_sample for i in labels] markers = np.array(list(chain(*markers))) tsne = TSNE(n_components=2) X_2d = tsne.fit_transform(X) fig, ax = plt.subplots() ax.tick_params(labelbottom=False) ax.tick_params(labelleft=False) marker_size = 5 handles = [] for i, s in enumerate(symbols): ind = np.where(markers == s)[0] h, = ax.plot(X_2d[:, 0][ind], X_2d[:, 1][ind], ls='none', c=colors[i], marker=s, markersize=marker_size) handles.append(h) legend_elements2 = [ Line2D([0], [0], marker=symbols[i], color='w', markerfacecolor=colors[i], markersize=marker_size) for i in range(6) # 6 companies ] ax.legend([(legend_elements2[0], legend_elements2[1]), (legend_elements2[2], legend_elements2[3]), (legend_elements2[4], legend_elements2[5])], ['Airline', 'Telecom', 'Public transport'], handler_map={tuple: HandlerTuple(ndivide=None)}, loc='upper right', title='Sectors', markerscale=1.4) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() plt.draw() fig.savefig('fig_tsne.png')
def _plot_automobile_legend(ax): from matplotlib.lines import Line2D from matplotlib.legend_handler import HandlerLine2D, HandlerTuple def _invisible(**style): return Line2D( [0], [0], c="w", markersize=12, markeredgecolor="#4863A0", **style ) p3 = _invisible( label="< 5 cylinders", marker="o", markerfacecoloralt="#D0D0D0", fillstyle="left", ) p4 = _invisible( label="≥ 5 cylinders", marker="^", markerfacecoloralt="#D0D0D0", fillstyle="left", ) ax.axis("off") lg1 = ax.legend(handles=[p3, p4], loc="center right", title="Number of cylinders") ax.add_artist(lg1) p11 = _invisible(label="Two doors", marker="o", markerfacecolor="white") p12 = _invisible(label="Two doors", marker="^", markerfacecolor="white") p21 = _invisible(label="Four doors", marker="o", markerfacecolor="#D0D0D0") p22 = _invisible(label="Four doors", marker="^", markerfacecolor="#D0D0D0") lg2 = ax.legend( [(p11, p12), (p21, p22)], ["Two doors", "Four doors"], numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None, pad=0.8)}, loc="center left", title="Number of doors", ) ax.add_artist(lg2)
def main(): args = parser.parse_args() N = args.num_of_points # number of grid points xmin = 0.0 # left boundary L = 1.0 # right boundary psi_0 = 0 # left Dirichlet bc psi_L = 0 # right Dirichlet bc x = np.linspace(xmin, L, N) _x = np.linspace(xmin, L, 1000) principal_quantum_numbers = list(range(1, 4)) nonreletivistic_energies = [] for n in principal_quantum_numbers: E = n**2 * h**2 / (8 * m_e * L) nonreletivistic_energies.append(E) # H psi = E psi # H = - hbar**2/(2*m_e) * d^2/dx^2 -> eigenvalue problem E, psi, pdf = fdm(N, xmin, L, bcs=(psi_0, psi_L)) fig, axs = plt.subplots(len(principal_quantum_numbers), 1, sharex='all', figsize=(7, 9)) for i, (n, E_analytic) in enumerate( zip(principal_quantum_numbers, nonreletivistic_energies)): l1, = axs[i].plot(_x, psi_close_form(_x, n, L), 'b-') l2, = axs[i].plot(_x, pdf_close_form(_x, n, L), 'r-') l3, = axs[i].plot(x, psi[:, i], 'bo', markersize=5, alpha=0.8) l4, = axs[i].plot(x, pdf[:, i], 'ro', markersize=5, alpha=0.8) pdf_analytic = pdf_close_form(x, n, L) axs[i].set_title( f'RMSE = {np.round(rmse(pdf_analytic, pdf[:, i]), 5)}') axs[i].legend([l1, l2, (l3, l4)], [r'$\psi(x)$', r'$|\psi(x)|^2$', 'FDM'], handler_map={tuple: HandlerTuple(ndivide=None)}) plt.xlabel(r'$x$') plt.tight_layout() plt.show()
def gradient_line_legend(color_maps, labels, num_points=10, handle_length=3): """ Creates a legend where each entry is a gradient color line. :param list color_maps: the color maps used in the legend. :param list[str] labels: the labels of the legend entries. :param int num_points: the number of points used to create the gradient. :param int handle_length: the length of the legend line entries. """ assert len(color_maps) == len( labels), 'Number of color maps has to be the same as that of labels!' color_space = np.linspace(0, 1, num_points) lines = [] for c_map in color_maps: lines.append( tuple( Line2D( [], [], marker='s', markersize=handle_length, c=c_map(c)) for c in color_space)) plt.legend(lines, labels, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}, handlelength=handle_length)
def plot_spectrum_datasets_off_regions(datasets, ax=None, legend=None, legend_kwargs=None, **kwargs): """Plot the off regions of spectrum datasets. Parameters ---------- datasets : `~gammapy.datasets.Datasets` of or sequence of `~gammapy.datasets.SpectrumDatasetOnOff` List of spectrum on-off datasets. ax : `~astropy.visualization.wcsaxes.WCSAxes` Axes object to plot on. legend : bool Whether to add/display the labels of the off regions in a legend. By default True if ``len(datasets) <= 10``. legend_kwargs : dict Keyword arguments used in `matplotlib.axes.Axes.legend`. The ``handler_map`` cannot be overridden. **kwargs : dict Keyword arguments used in `gammapy.maps.RegionNDMap.plot_region`. Can contain a `~cycler.Cycler` in a ``prop_cycle`` argument. Notes ----- Properties from the ``prop_cycle`` have maximum priority, except ``color``, ``edgecolor``/``color`` is selected from the sources below in this order: ``kwargs["edgecolor"]``, ``kwargs["prop_cycle"]``, ``matplotlib.rcParams["axes.prop_cycle"]`` ``matplotlib.rcParams["patch.edgecolor"]``, ``matplotlib.rcParams["patch.facecolor"]`` is never used. Examples -------- Plot forcibly without legend and with thick circles:: plot_spectrum_datasets_off_regions(datasets, ax, legend=False, linewidth=2.5) Plot that quantifies the overlap of off regions:: plot_spectrum_datasets_off_regions(datasets, ax, alpha=0.3, facecolor='black') Plot that cycles through colors (``edgecolor``) and line styles together:: plot_spectrum_datasets_off_regions(datasets, ax, prop_cycle=plt.cycler(color=list('rgb'), ls=['--', '-', ':'])) Plot that uses a modified `~matplotlib.rcParams`, has two legend columns, static and dynamic colors, but only shows labels for ``datasets1`` and ``datasets2``. Note that ``legend_kwargs`` only applies if it's given in the last function call with ``legend=True``:: plt.rc('legend', columnspacing=1, fontsize=9) plot_spectrum_datasets_off_regions(datasets1, ax, legend=True, edgecolor='cyan') plot_spectrum_datasets_off_regions(datasets2, ax, legend=True, legend_kwargs=dict(ncol=2)) plot_spectrum_datasets_off_regions(datasets3, ax, legend=False, edgecolor='magenta') """ import matplotlib.pyplot as plt from matplotlib.patches import Patch, CirclePolygon from matplotlib.legend_handler import HandlerTuple, HandlerPatch ax = ax or plt.gca(projection=datasets[0].counts_off.geom.wcs) legend = legend or legend is None and len(datasets) <= 10 legend_kwargs = legend_kwargs or {} handles, labels = [], [] kwargs.setdefault("facecolor", "none") prop_cycle = kwargs.pop("prop_cycle", plt.rcParams["axes.prop_cycle"]) plot_kwargs = kwargs.copy() for props, dataset in zip(prop_cycle(), datasets): props = props.copy() color = props.pop("color", plt.rcParams["patch.edgecolor"]) plot_kwargs["edgecolor"] = kwargs.get("edgecolor", color) plot_kwargs.update(props) dataset.counts_off.plot_region(ax, **plot_kwargs) # create proxy artist for the custom legend if legend: handle = Patch(**plot_kwargs) handles.append(handle) labels.append(dataset.name) if legend: legend = ax.get_legend() if legend: handles = legend.legendHandles + handles labels = [text.get_text() for text in legend.texts] + labels handles = [(handle, handle) for handle in handles] tuple_handler = HandlerTuple(ndivide=None, pad=0) def patch_func(legend, orig_handle, xdescent, ydescent, width, height, fontsize): radius = width / 2 return CirclePolygon((radius - xdescent, height / 2 - ydescent), radius) patch_handler = HandlerPatch(patch_func) legend_kwargs.setdefault("handletextpad", 0.5) legend_kwargs["handler_map"] = { Patch: patch_handler, tuple: tuple_handler } ax.legend(handles, labels, **legend_kwargs)
def plot_metadrop(stats): shot = stats[0]['htr'].shape[1] // 2 query = stats[0]['hte'].shape[1] // 2 n_sample = stats[0]['htr_sample'].shape[1] for i, stat in enumerate(stats): print('Processing {}/{}'.format(i + 1, len(stats))) for step in range(len(stat['htr'])): # Prepare points for fitting htr, hte = stat['htr'][step], stat['hte'][step] ytr, yte = stat['ytr'], stat['yte'] htr_sample = np.array(stat['htr_sample'][step]) htr_sample = htr_sample.reshape(n_sample * 2 * shot, -1) zipper = ArrayZipper([ len(htr), len(hte), len(htr_sample), ]) zipped_h = zipper.zip([ htr, hte, htr_sample, ]) zipped_y = zipper.zip([ ytr, yte, np.repeat(ytr, n_sample), ]) # Fit TSNE db_orthogonal = stat['w'][step][:, 0] - stat['w'][step][:, 1] db_orthogonal_unit = db_orthogonal / np.linalg.norm(db_orthogonal) projection = CustomTSNE(n_components=2, fixed_component=db_orthogonal_unit) htr_2d, hte_2d, htr_sample_2d = zipper.unzip( projection.fit_transform(zipped_h)) htr_sample_2d = htr_sample_2d.reshape(n_sample, 2 * shot, 2).swapaxes(0, 1) # Split class zipper = ArrayZipper([shot] * 2) htr_2d = zipper.unzip(htr_2d) htr_sample_2d = zipper.unzip(htr_sample_2d) zipper = ArrayZipper([query] * 2) hte_2d = zipper.unzip(hte_2d) # Plot plt.figure(dpi=300) # Data points cms = ['firebrick', 'royalblue'] markers = ['o', '^'] for c in range(2): for s in range(shot): # training data plt.scatter(htr_2d[c][s, 0], htr_2d[c][s, 1], marker=markers[s], s=300, c=cms[c], edgecolors='black', linewidths=1, zorder=7) # training with noise plt.scatter(htr_sample_2d[c][s, :, 0], htr_sample_2d[c][s, :, 1], marker=markers[s], s=300, c=cms[c], edgecolors='black', linewidths=1, linestyle=':', alpha=0.5, zorder=0) # test data plt.scatter(hte_2d[c][:, 0], hte_2d[c][:, 1], marker='*', s=300, c=cms[c], edgecolors='black', linewidths=1, zorder=3) db = (stat['b'][step][1] - stat['b'][step][0]) / np.linalg.norm(db_orthogonal) plt.axvline(db, c='black') # Custom legend train_markers = [] sample_markers = [] for s in range(shot): train_marker = plt.scatter([], [], c='none', marker=markers[s], edgecolor='black', linestyle='-', s=100) train_marker.remove() train_markers.append(train_marker) sample_marker = plt.scatter([], [], c='none', marker=markers[s], edgecolor='black', linestyle=':', s=100) sample_marker.remove() sample_markers.append(sample_marker) train_markers = tuple(train_markers) sample_markers = tuple(sample_markers) test_marker = matplotlib.lines.Line2D([], [], color='none', markeredgecolor='black', marker='*', linestyle='None', markersize=15) db_legend = matplotlib.lines.Line2D([], [], color='black', linestyle='-', label='decision boundary') plt.legend(handles=[ train_markers, sample_markers, test_marker, db_legend ], labels=[ 'train', 'perturbed train', 'test', 'decision boundary' ], prop={ 'size': 13 }, loc="lower left", handler_map={ train_markers: HandlerTuple(ndivide=2, pad=0.), sample_markers: HandlerTuple(ndivide=2, pad=0.), }).set_zorder(12) plt.axis('off') plt.tight_layout() path = os.path.join(args.savedir, 'plot/step{}'.format(step)) if not os.path.exists(path): os.mkdir(path) filename = '{}.png'.format(i) plt.tight_layout() plt.savefig(os.path.join(path, filename), bbox_inches='tight') plt.close()
def curve(json_files: List[TextIO], plot_params: PlotParams, close_fd: bool = True): fig = plt.figure(figsize=plot_params.fig_size) fig.set_tight_layout(plot_params.tight_layout) label_line = defaultdict(list) for json_file in json_files: line_params = LineParam(json_file=json_file, close_fd=close_fd, use_rate=plot_params.use_rate) line, = plt.plot(line_params.x_list, line_params.y_list, color=line_params.color, marker=line_params.marker, markersize=line_params.marker_size, markevery=line_params.mark_every, linewidth=line_params.line_width, linestyle=line_params.line_style, label=line_params.label) if plot_params.show_text and line_params.show_text: plt.text(x=line_params.text_x, y=line_params.text_y, s=line_params.label, c=line_params.text_color, fontsize=line_params.text_fontsize) label_line[line_params.label].append(line) del line_params plt.xscale(plot_params.xscale) plt.yscale(plot_params.yscale) if plot_params.xlim_low != DefaultVal.lim_low and plot_params.xlim_high != DefaultVal.lim_high: plt.xlim([plot_params.xlim_low, plot_params.xlim_high]) if plot_params.ylim_low != DefaultVal.lim_low and plot_params.ylim_high != DefaultVal.lim_high: plt.ylim([plot_params.ylim_low, plot_params.ylim_high]) plt.xlabel(xlabel=plot_params.xlabel, fontdict={ "weight": plot_params.xlabel_weight, "size": plot_params.xlabel_size }) plt.ylabel(ylabel=plot_params.ylabel, fontdict={ "weight": plot_params.ylabel_weight, "size": plot_params.ylabel_size }) if len(plot_params.yticks_val) != len(DefaultVal.empty_ticks): plt.yticks(plot_params.yticks_val, plot_params.yticks_text) if len(plot_params.xticks_val) != len(DefaultVal.empty_ticks): plt.xticks(plot_params.xticks_val, plot_params.xticks_text) # direction and size of ticks plt.tick_params(axis='x', labelsize=plot_params.tick_size, direction=plot_params.xtick_direction) plt.tick_params(axis='y', labelsize=plot_params.tick_size, direction=plot_params.ytick_direction) # v line for vline_x, vline_width, vline_color, vline_style, vline_label in \ zip(plot_params.vlines, plot_params.vline_width, plot_params.vline_color, plot_params.vline_style, plot_params.vline_label): line = plt.axvline(x=vline_x, linewidth=vline_width, color=vline_color, linestyle=vline_style, label=vline_label) if not plot_params.vline_label_hide: label_line[vline_label].append(line) # display grid if plot_params.show_grid: plt.grid(b=True, ls=plot_params.grid_linestyle) # hide which boarder ax = plt.gca() for direction in plot_params.no_boarder: ax.spines[direction].set_color('none') if plot_params.legend_loc != DefaultVal.legend: plt.legend([tuple(label_line[k]) for k in label_line.keys()], [label for label in label_line.keys()], handlelength=plot_params.legend_handle_length, loc=plot_params.legend_loc, fontsize=plot_params.legend_fontsize, handler_map={tuple: HandlerTuple(ndivide=1)}, frameon=plot_params.legend_frameon) plt.savefig(plot_params.save) plt.close(fig) pass
def compare_outerml_ring_cmlr(tab, mlb='i', cb1='g', cb2='r'): '''figure with comparison between aperture correction two M/L Parameters ---------- tab : astropy.table.Table full aggregation results table mlb : {str}, optional bandpass for mass-to-light ratio (the default is 'i', which [default_description]) cb1 : {str}, optional bluer bandpass for color (the default is 'g', SDSS g band) cb2 : {str}, optional redder bandpass for color (the default is 'r', SDSS r band) ''' cb1_nsa_mag = tab[f'mag_nsa_{cb1}'] cb2_nsa_mag = tab[f'mag_nsa_{cb2}'] broadband_color = cb1_nsa_mag - cb2_nsa_mag ml_cmlr_ring = tab['outerml_diff'] lum_frac_outer = tab[f'flux_outer_{mlb}'] / tab[f'flux_nsa_{mlb}'] valid = np.isfinite(tab['outerml_cmlr']) primarysample = m.mask_from_maskbits(tab['mngtarg1'], [10]) secondarysample = m.mask_from_maskbits(tab['mngtarg1'], [11]) fig, main_ax, hist_ax = make_panel_hist(top=0.875) for selection, label, marker, color in zip( [primarysample, secondarysample], ['Primary+', 'Secondary'], ['o', 'D'], ['r', 'b']): main_ax.scatter(x=broadband_color[selection * valid], y=ml_cmlr_ring[selection * valid], c=color, marker=marker, s=10. * lum_frac_outer[selection * valid], edgecolor='None', label=label, alpha=0.5) hist_ax.hist(ml_cmlr_ring[selection * valid], color=color, density=True, bins='auto', histtype='step', orientation='horizontal', linewidth=0.75) main_ax.legend(loc='lower right', prop={'size': 'xx-small'}) # make point size legend legend_lumfracs = np.array([.05, .1, .25, .5]) sc_pri = [main_ax.scatter( [], [], c='r', marker='o', s=10. * frac, edgecolor='None', alpha=0.5) for frac in legend_lumfracs] sc_sec = [main_ax.scatter( [], [], c='b', marker='D', s=10. * frac, edgecolor='None', alpha=0.5) for frac in legend_lumfracs] merged_markers = list(zip(sc_pri, sc_sec)) merged_labels = [r'{:.0f}\%'.format(frac * 100.) for frac in legend_lumfracs] hmap = {tuple: HandlerTuple(ndivide=None)} lumfrac_legend = hist_ax.legend( list(zip(sc_pri, sc_sec)), merged_labels, handler_map=hmap, loc='upper right', prop={'size': 'xx-small'}, title='\% flux outside IFU', title_fontsize='xx-small') main_ax.tick_params(labelsize='xx-small') main_ax.set_xlabel(r'${}-{}$'.format(cb1, cb2), size='x-small') main_ax.set_ylabel(r'$\log{\frac{\Upsilon^*_{\rm CMLR}}{\Upsilon^*_{\rm ring}}}$', size='x-small') main_ax.set_xlim([0.1, 0.9]) main_ax.set_ylim([-0.5, 0.5]) fig.suptitle(r'$\Upsilon^*_{\rm CMLR}$ vs $\Upsilon^*_{\rm ring}$', size='small') fig.savefig(os.path.join(csp_basedir, 'lib_diags/', 'outer_ml.png'))
fci2, = ax.plot([i*0.5 for i in range(len(split_omegas[1]))], split_omegas[1], c=(0.9,0.2,0.2), marker='.') fci3, = ax.plot([i*0.5 for i in range(len(split_omegas[2]))], split_omegas[2], c=(0.9,0.4,0.4), marker='.') secFci1, = ax.plot([i*0.5 for i in range(len(split_approx_omegas[0]))], split_approx_omegas[0], c=(0,0,0.9), marker='.') secFci2, = ax.plot([i*0.5 for i in range(len(split_approx_omegas[1]))], split_approx_omegas[1], c=(0.2,0.2,0.9), marker='.') secFci3, = ax.plot([i*0.5 for i in range(len(split_approx_omegas[2]))], split_approx_omegas[2], c=(0.4,0.4,0.9), marker='.') diff = np.sqrt((np.array(split_omegas[0]) - np.array(split_approx_omegas[0]))**2 + \ (np.array(split_omegas[1]) - np.array(split_approx_omegas[1]))**2 + \ (np.array(split_omegas[2]) - np.array(split_approx_omegas[2]))**2) er, = ax.plot([i*0.5 for i in range(len(diff))], diff, c='grey', marker='.') erbound, = ax.plot([i*0.5 for i in range(len(diff))], [np.sqrt(3*(omega_step_size/2.0)**2) for i in range(len(diff))], c='lightskyblue', marker='', linestyle='--') ax.legend([(secFci1,secFci2,secFci3),(fci1,fci2,fci3),er,erbound], [r'$\omega_{i,SecFCI}$', r'$\omega_{i,FCI}$', r'$|\underline{\omega}_{FCI}-\underline{\omega}_{SecFCI}|$', r'Error Bound'], numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}, loc=1, fontsize=FONT_SIZE) plt.xlabel(r'Time (s)', fontsize=FONT_SIZE) plt.ylabel(r'Values of $\omega_i$', fontsize=FONT_SIZE) ax.xaxis.set_tick_params(labelsize=FONT_SIZE) ax.yaxis.set_tick_params(labelsize=FONT_SIZE) # Move the legend up slightly ax.xaxis.labelpad = 0 plt.tight_layout() if SAVE_NOT_SHOW: plt.savefig('images/omegas_cmp.pdf') else: plt.show() plt.close()
fig, (ax1, ax2) = plt.subplots(2, 1) # First plot: two legend keys for a single entry p1 = ax1.scatter([1], [5], c='r', marker='s', s=100) p2 = ax1.scatter([3], [2], c='b', marker='o', s=100) # `plot` returns a list, but we want the handle - thus the comma on the left p3, = ax1.plot([1, 5], [4, 4], 'm-d') # Assign two of the handles to the same legend entry by putting them in a tuple # and using a generic handler map (which would be used for any additional # tuples of handles like (p1, p3)). l = ax1.legend([(p1, p3), p2], ['two keys', 'one key'], scatterpoints=1, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}) # Second plot: plot two bar charts on top of each other and change the padding # between the legend keys x_left = [1, 2, 3] y_pos = [1, 3, 2] y_neg = [2, 1, 4] rneg = ax2.bar(x_left, y_neg, width=0.5, color='w', hatch='///', label='-1') rpos = ax2.bar(x_left, y_pos, width=0.5, color='k', label='+1') # Treat each legend entry differently by using specific `HandlerTuple`s l = ax2.legend( [(rpos, rneg), (rneg, rpos)], ['pad!=0', 'pad=0'], handler_map={ (rpos, rneg): HandlerTuple(ndivide=None),
def plot_ESP_impact(mc): plt.close('all') init_class_size = pd.read_csv('monte_carlo/inital_pop_by_class.csv', header=None, index_col=0).squeeze() ################################### ################################### # ADEQUACY OF BENEFITS ################# adequacy = pd.read_csv('monte_carlo/{}/ESP_adequacy.csv'.format( mc.shock_code), index_col=0) ie2plot = [0, 25, 50, 75, 100] for nie, ie in enumerate(ie2plot): plt.bar([ _ * (len(ie2plot) + 1) + nie + 0.5 for _ in range(len(mc.classes)) ], [adequacy['{}_ie{}'.format(_, ie)].mean() for _ in mc.classes], linewidth=0, facecolor=blues_pal[nie], alpha=0.6, zorder=90) if nie == 0: for _n, _ie in enumerate(ie2plot): _x = float(nie + _n + 0.8) _y = float(adequacy['{}_ie{}'.format('sub', _ie)].mean()) annostr = 'perfect targeting' if _n == 0 else ( '{}% eligibility error'.format(_ie) ) # if _n == 1 else '{}%'.format(_ie)) plt.annotate( annostr, xy=(_x, _y), xytext=(_x + 1, _y + 0.15), fontsize=8, style='italic', arrowprops=dict( arrowstyle="-", color="0.5", shrinkA=5, shrinkB=5, patchA=None, patchB=None, connectionstyle="angle,angleA=180,angleB=-90,rad=5", relpos=(0, 0.5))) plt.xticks([ _ * (len(ie2plot) + 1) + (len(ie2plot) + 1) / 2 for _ in range(len(mc.classes)) ], [_ for _ in mc.class_labels], fontsize=8, style='italic') plt.xlabel('Pre-COVID income class', labelpad=10, linespacing=1.5) plt.yticks([1, 2, 3], ['100%\nmonthly\nlosses', '200%', '300%'], fontsize=8, style='italic') plt.ylabel( 'Social Amelioration Program adequacy\n(affected households only)', labelpad=8, linespacing=1.5) sns.despine(left=True) plt.grid(True, which='major', axis='y', zorder=10) plt.savefig('figs/sp_ESP_adequacy.pdf', format='pdf', bbox_inches='tight') plt.close('all') ################################### ################################### # EXTREME POVERTY ################# epov_base = pd.read_csv('monte_carlo/{}/totpop_sub.csv'.format( mc.shock_code), index_col=0).mean(axis=0) epov = pd.read_csv('monte_carlo/{}/ESP_subsistence.csv'.format( mc.shock_code), index_col=0) ie2plot = [0, 25, 50, 75, 100] pie_1 = [[] for _ in ie2plot] pie_2 = [[] for _ in ie2plot] ntl_1 = [None for _ in ie2plot] ntl_2 = [None for _ in ie2plot] for nie, ie in enumerate(ie2plot): ntl_1[nie] = round( sum([ epov_base[_] - epov['{}_ie{}'.format(_, ie)].mean() for _ in mc.classes ]), 1) ntl_2[nie] = round( sum([epov['{}_ie{}'.format(_, ie)].mean() for _ in mc.classes]), 1) for _n, _ in enumerate(mc.classes): _a = 0.9 if _ == 'sub' else 0.20 pie_1[nie].append( plt.bar([_n * (len(ie2plot) + 1) + nie + 0.5], [epov_base[_] - epov['{}_ie{}'.format(_, ie)].mean()], linewidth=0, facecolor=blues_pal[nie], alpha=_a, zorder=90)) _a = 0.20 if _ == 'sub' else 0.9 pie_2[nie].append( plt.bar([_n * (len(ie2plot) + 1) + nie + 0.5], [-epov['{}_ie{}'.format(_, ie)].mean()], linewidth=0, facecolor=reds_pal[nie], alpha=_a, zorder=90)) # mark initial incidence of extreme poverty # if nie == 0: # for _n,_ in enumerate(['sub']): # plt.plot([_n*(len(ie2plot)+1)+nie+0,_n*(len(ie2plot)+1)+nie+5],[-init_class_size[_],-init_class_size[_]],color=greys_pal[6],ls=':',lw=1,alpha=0.8) # plt.annotate('extreme poverty\npre-COVID incidence',xy=(_n*(len(ie2plot)+1)+nie+2.5,-init_class_size[_]+0.1),fontsize=7, # color=greys_pal[6],ha='center',va='bottom',style='italic') _ytext = -1 if nie == 0: for _n, _ie in enumerate(ie2plot): _x = float(nie * (len(ie2plot) + 1) + _n + 0.8) epov_subset = epov[[ _c for _c in epov.columns if '_ie{}'.format(_ie) in _c ]].mean(axis=0).to_frame().T epov_subset = epov_subset.rename(columns={ _c: _c.replace('_ie{}'.format(_ie), '') for _c in epov.columns }) _y = epov_base['sub'] - epov['{}_ie{}'.format('sub', _ie)].mean() _ytext = max( float((epov_base.to_frame().T - epov_subset).max(axis=1)) + 1.4, _ytext) annostr = 'perfect targeting' if _n == 0 else ( '{}% eligibility error'.format(_ie) ) # if _n == 1 else '{}%'.format(_ie)) plt.annotate( annostr, xy=(_x, _y), xytext=(_x + 1, _ytext - 0.50 * _n), fontsize=8, weight=500, annotation_clip=False, arrowprops=dict( arrowstyle="-", color="0.5", shrinkA=5, shrinkB=5, patchA=None, patchB=None, connectionstyle="angle,angleA=180,angleB=-90,rad=5", relpos=(0, 0.5))) lgd = plt.gca().legend( [(pie_1[nie][0], pie_2[nie][4]) for nie in range(len(ie2plot))], [ '{} m. / {} m.'.format(ntl_1[nie], ntl_2[nie]) for nie in range(len(ie2plot)) ], loc='upper right', labelspacing=0.75, ncol=1, fontsize=8, borderpad=0.75, fancybox=True, frameon=True, framealpha=0.9, title='Total avoided / remain', handler_map={tuple: HandlerTuple(ndivide=None, pad=0)}) lgd.get_title().set_fontsize('8') # Arrow for y-axis x_lo = -1 x_lim = [x_lo, plt.gca().get_xlim()[1]] # plt.ylabel('Extreme poverty reduction due to\nSocial Amelioration Program [millions]',labelpad=12,linespacing=2.) plt.arrow(x_lo / 2, 0, 0, 6, clip_on=False, ec=blues_pal[0], fc='white', alpha=0.4, width=0.35, head_width=0.35, head_length=0.21, linewidth=2.5) plt.arrow(x_lo / 2, 0, 0, -4, clip_on=False, ec=reds_pal[0], fc='white', alpha=0.4, width=0.35, head_width=0.35, head_length=0.21, linewidth=2.5) plt.annotate('Kept out of extreme\npoverty by SAP [mil.]', xy=(3.5 * x_lo, 3), rotation=90, va='center', ha='center', annotation_clip=False, fontsize=9, linespacing=1.8) plt.annotate('Not kept out of extreme\npoverty by SAP [mil.]', xy=(3.5 * x_lo, -2), rotation=90, va='center', ha='center', annotation_clip=False, fontsize=9, linespacing=1.8) plt.plot([x_lo / 2, x_lim[1]], [0, 0], zorder=99, linewidth=0.75, color=greys_pal[6], alpha=0.9) plt.xlim(x_lo) plt.xticks([ _ * (len(ie2plot) + 1) + (len(ie2plot) + 0.5) / 2 for _ in range(len(mc.classes)) ], [_ for _ in mc.class_labels], fontsize=8, ha='center') plt.xlabel('pre-COVID income class', labelpad=9, linespacing=1.5, fontsize=9) plt.yticks([2 * _ for _ in range(-2, 4)], [abs(2 * _) for _ in range(-2, 4)], fontsize=8) sns.despine(left=True, bottom=True, trim=True) #plt.gca().xaxis.tick_top() plt.grid(True, which='major', axis='y', zorder=10, alpha=0.2) plt.savefig('figs/sp_ESP_subsistence.pdf', format='pdf', bbox_inches='tight') plt.close('all') ################################### ################################### # POVERTY ######### # drop subsustence from mc.classes: # mc.classes = mc.classes[1:] # mc.class_labels = mc.class_labels[1:] pov_base = pd.read_csv('monte_carlo/{}/totpop_pov.csv'.format( mc.shock_code), index_col=0).mean(axis=0) pov = pd.read_csv('monte_carlo/{}/ESP_poverty.csv'.format(mc.shock_code), index_col=0) ie2plot = [0, 25, 50, 75, 100] pie_1 = [[] for _ in ie2plot] pie_2 = [[] for _ in ie2plot] ntl_1 = [None for _ in ie2plot] ntl_2 = [None for _ in ie2plot] for nie, ie in enumerate(ie2plot): ntl_1[nie] = round( sum([ pov_base[_] - pov['{}_ie{}'.format(_, ie)].mean() for _ in mc.classes ]), 1) ntl_2[nie] = round( sum([pov['{}_ie{}'.format(_, ie)].mean() for _ in mc.classes]), 1) for _n, _ in enumerate(mc.classes): _a = 0.9 if _ == 'sub' or _ == 'pov' else 0.20 pie_1[nie].append( plt.bar([_n * (len(ie2plot) + 1) + nie + 0.5], [pov_base[_] - pov['{}_ie{}'.format(_, ie)].mean()], linewidth=0, facecolor=blues_pal[nie], alpha=_a, zorder=90)) _a = 0.20 if _ == 'sub' or _ == 'pov' else 0.9 pie_2[nie].append( plt.bar([_n * (len(ie2plot) + 1) + nie + 0.5], [-pov['{}_ie{}'.format(_, ie)].mean()], linewidth=0, facecolor=reds_pal[nie], alpha=_a, zorder=90)) # mark initial incidence of extreme poverty # if nie == 0: # for _n,_ in enumerate(['sub','pov']): # plt.plot([_n*(len(ie2plot)+1)+nie+0.5,_n*(len(ie2plot)+1)+nie+5.25],[-init_class_size[_],-init_class_size[_]],color=greys_pal[6],ls=':',lw=1,alpha=0.8) # if _ == 'pov': plt.annotate('pre-COVID\npoverty incidence',xy=(_n*(len(ie2plot)+1)+nie+3.0,-init_class_size[_]+0.3),fontsize=7, # color=greys_pal[6],ha='center',va='bottom',style='italic') _ytext = -1 if nie == 1: for _n, _ie in enumerate(ie2plot): _x = float(nie * (len(ie2plot) + 1) + _n + 0.8) pov_subset = pov[[ _c for _c in pov.columns if '_ie{}'.format(_ie) in _c ]].mean(axis=0).to_frame().T pov_subset = pov_subset.rename(columns={ _c: _c.replace('_ie{}'.format(_ie), '') for _c in pov.columns }) _y = pov_base['pov'] - pov['{}_ie{}'.format('pov', _ie)].mean() _ytext = max( float((pov_base.to_frame().T - pov_subset).max(axis=1)) + 2.75, _ytext) annostr = 'perfect targeting' if _n == 0 else '{}% eligibility error'.format( _ie) plt.annotate( annostr, xy=(_x, _y), xytext=(_x + 1, _ytext - 1.2 * _n), fontsize=8, weight=500, annotation_clip=False, arrowprops=dict( arrowstyle="-", color="0.5", shrinkA=5, shrinkB=5, patchA=None, patchB=None, connectionstyle="angle,angleA=180,angleB=-90,rad=5", relpos=(0, 0.5))) lgd = plt.gca().legend( [(pie_1[nie][0], pie_2[nie][4]) for nie in range(len(ie2plot))], [ '{} m. / {} m.'.format(ntl_1[nie], ntl_2[nie]) for nie in range(len(ie2plot)) ], loc='upper right', labelspacing=0.75, ncol=1, fontsize=8, borderpad=0.75, fancybox=True, frameon=True, framealpha=0.9, title='Total avoided / remain', handler_map={tuple: HandlerTuple(ndivide=None, pad=0)}) lgd.get_title().set_fontsize('8') # Arrow for y-axis x_lo = -1 x_lim = [x_lo, plt.gca().get_xlim()[1]] plt.arrow(x_lo / 2, 0, 0, 12, clip_on=False, ec=blues_pal[0], fc='white', alpha=0.4, width=0.35, head_width=0.35, head_length=0.67, linewidth=2.5) plt.arrow(x_lo / 2, 0, 0, -12, clip_on=False, ec=reds_pal[0], fc='white', alpha=0.4, width=0.35, head_width=0.35, head_length=0.67, linewidth=2.5) plt.plot([x_lo / 2, x_lim[1]], [0, 0], zorder=99, linewidth=0.75, color=greys_pal[6], alpha=0.9) x_lim[0] = x_lo plt.xticks([ _ * (len(ie2plot) + 1) + (len(ie2plot) + 1) / 2 for _ in range(len(mc.classes)) ], [_ for _ in mc.class_labels], fontsize=8) plt.xlabel('pre-COVID income class', labelpad=10, linespacing=1.5, fontsize=9) plt.yticks([4 * _ for _ in range(-3, 4)], [abs(4 * _) for _ in range(-3, 4)], fontsize=8) plt.xlim(x_lo) # plt.ylim(-12,12) # plt.ylabel('Poverty reduction due to\nSocial Amelioration Program [millions]',labelpad=12,linespacing=2.) plt.annotate('Kept out of poverty\nby SAP [mil.]', xy=(3 * x_lim[0], 6), rotation=90, va='center', ha='center', annotation_clip=False, fontsize=9, linespacing=1.75) plt.annotate('Not kept out of\npoverty by SAP [mil.]', xy=(3 * x_lim[0], -6), rotation=90, va='center', ha='center', annotation_clip=False, fontsize=9, linespacing=1.75) sns.despine(left=True, bottom=True, trim=True) #plt.gca().xaxis.tick_top() plt.grid(True, which='major', axis='y', zorder=10, alpha=0.2) plt.savefig('figs/sp_ESP_poverty.pdf', format='pdf', bbox_inches='tight') plt.close('all')
def plot_tradeoff(best,frontiers,saving=False): # fig, ax = plt.subplots(figsize=(10,10)) fig = plt.figure(figsize=(10,10)) axes = {} cmap = plt.cm.get_cmap('cividis') # norm = Normalize(vmin=min([weight for weight in weights if weight > 0]), vmax=max(weights)) norm = MidpointNormalize(vmin=min(weights),vmax=max(weights),midpoint=np.median(weights)) sm = ScalarMappable(norm=norm, cmap=cmap) # sm.to_rgba(other_fn.weight) # colors = get_n_colors(len(all_objectives_for_frontier_and_obj)) color_map = {fn.weightstr : sm.to_rgba(fn.weight) for fn in best} #colors.pop() # marker_map = {fn : f"${fn.marker}^{{{fn.weight}}}$" for fn in best} line_artists = [] # point_legend_helper = {fn : (color_map[fn],fn.marker,fn.basename) for fn in best} scat = {fn : [] for fn in frontiers} scat_xdata = [instance.fstars_type0[fn] for i,(fn,frontier) in enumerate(frontiers.items()) for (other_fn,instance) in best.items()] scat_ydata = [instance.fstars[fn] for i,(fn,frontier) in enumerate(frontiers.items()) for (other_fn,instance) in best.items()] marker_size = 0.05 def get_nonoverlapping_positions(x_data, y_data): new_x = x_data.copy() new_y = y_data.copy() numel = len(new_x) for index, (x, y) in enumerate(zip(new_x,y_data)): to_change = [] for index2 in range(index+1,numel): other_x = new_x[index2] other_y = y_data[index2] if abs(x-other_x) < marker_size and abs(y-other_y) < marker_size: to_change.append(index2) for index2 in to_change: # print(f"Adjusting new_x[{index2}] = {new_x[index2]},y_data[{index2}] = {y_data[index2]}") new_x[index2] += marker_size*0.2 new_y[index2] += marker_size*0.05 return new_x,new_y scat_xdata_adjusted,scat_ydata_adjusted = get_nonoverlapping_positions(scat_xdata,scat_ydata) ctr = 0 for i, (fn, frontier) in enumerate(frontiers.items()): ax = fig.add_subplot(111,label=fn.__name__,frame_on=False) cbar = fig.colorbar(sm,ax=ax,drawedges=False) cbar.ax.set_ylabel(f"{colorbar_label}") axes[fn] = ax x_raw = frontier.fstarvals_type0() y_raw = frontier.fstarvals() print(f"Plotting data for {fn.__name__}") color = color_map[fn.weightstr] linename = f"{fn.__name__} Efficient Frontier" ax.plot(x_raw,y_raw,label=linename,color="black",marker="4",alpha=0.7) line_artists.extend(ax.collections.copy() + ax.lines.copy()) print(f"Scattering for {fn.__name__}") for other_fn, instance in best.items(): if True: #other_fn != fn: print(f"{other_fn.__name__}, ({instance.fstars_type0[fn]},{instance.fstars[fn]}), marker: {other_fn.weighted_marker}") x_inst = instance.fstars_type0[fn]# + np.random.rand()/200 #jittering # x_inst_adjusted = x_inst y_inst = instance.fstars[fn]# + np.random.rand()/200 #jittering # y_inst_adjusted = scat_ydata_adjusted[ctr] # x_inst = scat_xdata_adjusted[ctr] # y_inst = scat_ydata_adjusted[ctr] ctr += 1 # label = other_fn.__name__ label = f"{other_fn.__name__}" scatcolor = color_map[other_fn.weightstr] scatplot = ax.scatter([x_inst],[y_inst],label=label,s=20**2,color=scatcolor,marker=other_fn.weighted_marker,alpha=0.8) # arrow_size = marker_size/100 # arrow = ax.arrow(x_inst, y_inst_adjusted,0,y_inst-y_inst_adjusted, color='red',alpha=0.3, width=arrow_size*0.1, head_width=arrow_size, head_length=marker_size*0.5, zorder=0,length_includes_head=True) fakelabel = f"{other_fn.basename}" fakescatplot = matplotlib.lines.Line2D([], [],label=fakelabel,markersize=20,color=scatcolor,marker=other_fn.basemarker,alpha=0.8,linestyle='None') # scat[fn].append(scatplot) scat[fn].append(fakescatplot) # fakescatplot = matplotlib.lines.Line2D([], [],label="hi",markersize=20,color="red",marker="+",alpha=0.8,linestyle='None') ax.set_xticks([]) ax.set_yticks([]) ax.tick_params(axis='x', labelcolor=color) ax.tick_params(axis='y', labelcolor=color) # artists = [artist for ax in axes for artist in ax.collections.copy() + ax.lines.copy()] legend_dict = {artist.properties().get('label') : artist for artist in line_artists} scat_dict = {} for fn,art_list in scat.items(): for artist in art_list: artist_lab = artist.properties().get('label') scat_dict_key = f"Optimal {artist_lab}" if not scat_dict.get(scat_dict_key): scat_dict[scat_dict_key] = [] scat_dict[scat_dict_key].append(artist) for k,l in scat_dict.items(): scat_dict[k].sort(key = lambda artist: str(artist.get_markeredgecolor())) scat_dict[k] = tuple(l) legend_dict = {**legend_dict,**scat_dict} print(scat_dict) plt.legend(legend_dict.values(),legend_dict.keys(),loc='lower left',handler_map={tuple: HandlerTuple(ndivide=None)},labelspacing=0.9,handlelength=3.5) #,handletextpad=1.0,loc="upper right"bbox_to_anchor=(0.5, 0), ncol=len(legend_dict),fontsize='small' # plt.setp(fig.get_axes(), xticks=[], yticks=[]) ax.set_xlabel(f"Utility to type-$0$ Individuals") ax.set_ylabel(f"Utility to Population") weight_string = ", ".join([str(weight) for weight in weights]) plt.title(title) plt.show(block=False) if saving: plt.savefig(f"figures/frontier_{trial_label}_{generate_file_label()}.pdf", bbox_inches='tight') return fig,axes,scat
import matplotlib.pyplot as plt from matplotlib.legend_handler import HandlerTuple fig, (ax1, ax2) = plt.subplots(2, 1) # First plot: two legend keys for a single entry p1 = ax1.scatter([1], [5], c='r', marker='s', s=100) p2 = ax1.scatter([3], [2], c='b', marker='o', s=100) # `plot` returns a list, but we want the handle - thus the comma on the left p3, = ax1.plot([1, 5], [4, 4], 'm-d') # Assign two of the handles to the same legend entry by putting them in a tuple # and using a generic handler map (which would be used for any additional # tuples of handles like (p1, p3)). l = ax1.legend([(p1, p3), p2], ['two keys', 'one key'], scatterpoints=1, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}) # Second plot: plot two bar charts on top of each other and change the padding # between the legend keys x_left = [1, 2, 3] y_pos = [1, 3, 2] y_neg = [2, 1, 4] rneg = ax2.bar(x_left, y_neg, width=0.5, color='w', hatch='///', label='-1') rpos = ax2.bar(x_left, y_pos, width=0.5, color='k', label='+1') # Treat each legend entry differently by using specific `HandlerTuple`s l = ax2.legend([(rpos, rneg), (rneg, rpos)], ['pad!=0', 'pad=0'], handler_map={(rpos, rneg): HandlerTuple(ndivide=None), (rneg, rpos): HandlerTuple(ndivide=None, pad=0.)})
plt.ylabel(r'$\rho/\rho_R$', fontsize = 20) plt.legend() plt.savefig('Density_'+str(case)+'.eps', bbox_inches='tight') plt.figure(4) plt.xlabel(r'$x$' , fontsize = 20) plt.ylabel(r'$X_i$', fontsize = 20) df=pd.read_csv('Spec.csv', sep='\t',header=None) xExact = np.array(df)[:,0] YiExact = np.array(df)[:,1:6] XiExact = YiExact for i, y in enumerate(YiExact): XiExact [i,:] = Yi2Xi(YiExact[i,:]) line = [] lable = [] for isp, sp in enumerate(SpNames): l1, = plt.plot( x, Xi[:,isp], '-') l2, = plt.plot(xExact, XiExact[:,isp], 'x', color=l1.get_color()) lable.append(r'$X_{'+sp.decode()+'}$') line.append((l1, l2)) plt.legend(line, lable, handler_map={tuple: HandlerTuple(ndivide=None)}, handlelength=8.0) plt.savefig('Species_'+str(case)+'.eps', bbox_inches='tight') return x, u, p, rho plt.rcParams.update({'font.size': 12}) x, u, p, r = process(600, 0) plt.show()
def plot_training_history(self, figsize): figure, axes = self.__plot_parameters(figsize=figsize) gs = GridSpec(nrows=3, ncols=1, figure=figure, height_ratios=[1, 0.01, 1]) axes_0 = plt.subplot(gs[0]) axes_1 = plt.subplot(gs[1]) axes_2 = plt.subplot(gs[2]) accuracy_plot = sb.lineplot(data=self.accuracy, palette=sb.color_palette( ['#C8102E', '#00B388']), dashes=False, ax=axes_0) handles, _ = axes_0.get_legend_handles_labels() acc_point = axes_0.scatter(x=self.best_model['accuracy'][0], y=self.best_model['accuracy'][1], s=200, c='#888B8D', marker='1', linewidth=2, zorder=3) val_acc_point = axes_0.scatter(x=self.best_model['val_accuracy'][0], y=self.best_model['val_accuracy'][1], s=200, c='#888B8D', marker='2', linewidth=2, zorder=3) axes_0.get_legend().remove() axes_0.set_xticks(ticks=[]) accuracy_plot.set(title=(f'{self.name} {self.model_name} ' f'Training History'), ylabel='Accuracy') handles = sum([handles, [(val_acc_point, acc_point)]], []) axes_1.legend(handles=handles, labels=['Training', 'Validation', 'Best Model'], loc='center', ncol=3, scatterpoints=2, frameon=False, borderaxespad=0, handler_map={tuple: HandlerTuple(ndivide=None, pad=0.8)}) axes_1.axis('off') loss_plot = sb.lineplot(data=self.loss, palette=sb.color_palette( ['#C8102E', '#00B388']), dashes=False, legend=False, ax=axes_2) axes_2.scatter(x=self.best_model['loss'][0], y=self.best_model['loss'][1], s=200, c='#888B8D', marker='2', linewidth=2, zorder=3) axes_2.scatter(x=self.best_model['val_loss'][0], y=self.best_model['val_loss'][1], s=200, c='#888B8D', marker='1', linewidth=2, zorder=3) loss_plot.set(xlabel='Epoch', ylabel='Loss') figure.savefig(fname=f"{self.evaluate_CNN_path}/training-history.svg", format='svg') plt.close(fig=figure)
def __init__(self, **kwargs): HandlerTuple.__init__(self, **kwargs)
null_2[t_2 < 8] = True plt.xlabel(r'T/\si{\kelvin}') plt.ylabel(r'I/\si{\pico\ampere}') params_2, erros_2, p_2 = plotfit(T_2, I_2, Exponentieller_Untergrund, None, slice_=null_2, fullfit=True, save=False, p0=(0.42, 0.08, -0.42)) p2, = plt.plot(T_2[~null_2], I_2[~null_2], 'b.') plt.legend([(p_2[0], p2), (p_2[1])], ['Messwerte', 'Exponentieller Untergrund'], handler_map={tuple: HandlerTuple(ndivide=None)}) plt.savefig('build/I_mit_untergrund_2.pdf') plt.clf() print("Exponentieller Untergrund 2Grad/min") print("a, b, c") print(params_2) print(erros_2) print() null_15 = t_15 > 78 null_15[t_15 < 42] = True null_15[t_15 < 40] = False null_15[t_15 < 7] = True plt.xlabel(r'T/\si{\kelvin}') plt.ylabel(r'I/\si{\pico\ampere}') params_15, erros_15, p_15 = plotfit(T_15,
def main(): colors = ['#000000', '#01545a', '#ed0345', '#ef6932'] #labels=[r'$O^A$',r'$O^B$',r'$O^C$',r'$O^D$'] #labels=[r'clean O-t',r'hydro O-t',r'clean $CeO_4$-t',r'hydro $CeO_4$-t'] labels = [ r'clean surface', r'hydro surface', r'clean surface', r'hydro surface' ] x = np.array([1.91, 1.08, 0.89, 1.13]) #空穴形成能 y = np.array([0.70, 0.58, 0.18, 0.25]) #barrier1 z = np.array([0.85, 0.60, 0.26, 0.50]) #barrier2 x_fit = np.array([1.91, 1.08, 0.89, 1.13]) y_fit = np.array([0.70, 0.58, 0.18, 0.25]) z_fit = np.array([0.85, 0.60, 0.26, 0.50]) fig = plt.figure(figsize=(8, 6)) #plt.subplots_adjust(wspace=0.5) ax1 = fig.add_subplot(111) markers = ['o', 'o', 'o', 'o'] fill_styles = ['full', 'none', 'full', 'none'] points_1 = [] points_2 = [] for x_, y_, z_, marker, fill_style, label in zip(x, y, z, markers, fill_styles, labels): points_1.append( ax1.plot(x_, y_, marker, fillstyle=fill_style, color='#01545a', label=label)) points_2.append( ax1.plot(x_, z_, marker, fillstyle=fill_style, color='#ed0345', label=label)) x_major_locator = MultipleLocator(0.2) #把x轴的刻度间隔设置为0.2,并存在变量里 ax1.xaxis.set_major_locator(x_major_locator) #ymajorFormatter=FormatStrFormatter('%.1f') #设置y轴主刻度小数位数 #ax1.yaxis.set_major_formatter(ymajorFormatter) regr = LinearRegression() regr.fit(x_fit.reshape(-1, 1), y_fit) line_1 = ax1.plot(x_fit, regr.predict(x_fit.reshape(-1, 1)), color='#01545a', label=r'E$_{a1}$') regr = LinearRegression() regr.fit(x_fit.reshape(-1, 1), z_fit) line_2 = ax1.plot(x_fit, regr.predict(x_fit.reshape(-1, 1)), color='#ed0345', label=r'$E_{a2}$') plt.text(1.4, 0.45, r"$R^2=0.60$", color='#01545a', fontsize=16) plt.text(1.15, 0.6, r"$R^2=0.83$", color='#ed0345', fontsize=16) plt.xticks(fontsize=16) plt.yticks(fontsize=16) plt.xlabel(r'$E_{v}$ / eV', fontsize=18) plt.ylabel(r'$E_{a}$ / eV', fontsize=18) labels = [r'clean surface', r'hydro surface', r'$E_{a1}$', r'$E_{a2}$'] #first_legend=plt.legend([(points_1[i][0],points_2[i][0]) for i in range(4)],labels,handler_map={tuple: HandlerTuple(ndivide=None)},fontsize=14,ncol=2) first_legend = plt.legend([(points_1[i][0], points_2[i][0]) for i in range(2)] + [line_1[0], line_2[0]], labels, handler_map={tuple: HandlerTuple(ndivide=None)}, fontsize=14, ncol=2)
def plot_chart(plot_type=None): #======================================================================================================== # User-defined settings #======================================================================================================== #Whether to save image or display. "directory_path" string is ignored if setting==False. save_image = { 'setting': True, 'directory_path': "full_directory_path_here" } #What to plot (confirmed, confirmed_normalized, deaths, recovered, active, daily) if plot_type == None: plot_type = "active" #Include repatriated cases (e.g., cruises)? include_repatriated = False #Plot total numbers? plot_total = True #Over how many days should the doubling rate be calculated? lag_days = 7 #Additional settings settings = { 'log_y': True, #Use logarithmic y-axis? 'condensed_plot': True, #Condensed plot? (small dots and narrow lines) 'highlight_state': 'New York', #Highlight state? 'number_of_state': 20, #Limit number of states plotted? } #======================================================================================================== # Get COVID-19 case data #======================================================================================================== #Z-Order: # 2-highlighted trend # 3-total trend # 4-highlighted state dot # 5-total dot # 6-state dots repatriated_locations = ['diamond princess', 'grand princess'] """ COVID-19 case data is retrieved from Johns Hopkins CSSE: https://github.com/CSSEGISandData/COVID-19 """ abbr_state = read_data.abbr_state() state_abbr = {v: k for k, v in abbr_state.items()} #Avoid re-reading case data if it's already stored in memory try: cases except: print("--> Reading in COVID-19 case data from Johns Hopkins CSSE") output = read_data.read_us() dates = output['dates'] cases = output['cases'] #======================================================================================================== # Create plot based on type #======================================================================================================== max_value = 0 max_doubling = -6 min_doubling = 6 lag_index = -lag_days - 1 highlighted_series = [] #Create figure fig, ax = plt.subplots(figsize=(9, 6), dpi=125) #Total count total_count = np.array([0.0 for i in cases['diamond princess']['date']]) total_count_rp = np.array([0.0 for i in cases['diamond princess']['date']]) #Iterate through every region sorted_keys = [ y[1] for y in sorted([(np.nanmax(cases[x][plot_type]), x) for x in cases.keys()]) ][::-1] sorted_value = [ y[0] for y in sorted([(np.nanmax(cases[x][plot_type]), x) for x in cases.keys()]) ][::-1] for idx, (key, value) in enumerate(zip(sorted_keys, sorted_value)): end_day = cases[key][plot_type][-1] start_day = cases[key][plot_type][lag_index] day_after_start = cases[key][plot_type][lag_index + 1] doubling_time = 999 inverse_doubling_time = 999 if end_day > 1: if start_day > 0 and end_day != start_day and start_day != day_after_start: doubling_time = lag_days * np.log(2) / np.log( end_day / start_day) inverse_doubling_time = 1 / doubling_time #Special handling for Diamond Princess if include_repatriated == False and key in repatriated_locations: continue #Total count if key not in repatriated_locations: total_count += np.array(cases[key][plot_type]) total_count_rp += np.array(cases[key][plot_type]) #Plot states, including highlighted state if applicable. if inverse_doubling_time != 999: # Plot highlighted state if 'highlight_state' in settings.keys( ) and settings['highlight_state'].lower() == key.lower(): highlight_color = 'red' highlight_key = f"{key.title()}" highlight_doubling = f"{doubling_time:.1f}" highlight_total = f"{end_day}" kwargs = {'zorder': 4, 'color': highlight_color} ax.scatter(inverse_doubling_time, end_day, **kwargs) highlighted_series = cases[key][plot_type] # Plot rest of states else: country_text_color = 'k' ST = state_abbr.get(key.title()) if (ST == None): print(key.title(), ST) kwargs = { 'zorder': 6, 'color': country_text_color, 'ha': 'center', 'va': 'center', 'family': 'monospace', 'fontsize': 8 } ax.text(inverse_doubling_time, end_day, ST, **kwargs) #Output stats to terminal print( f"{key.title()}\t{start_day}->{end_day}\t{doubling_time:.2f}") #Store values useful for the plot axes. max_value = max(max_value, end_day) max_doubling = max(max_doubling, inverse_doubling_time) min_doubling = min(min_doubling, inverse_doubling_time) print(f"\nRange: {1/min_doubling:.2f} to {1/max_doubling:.2f} days") #Calculate highlighted state running doubling time if 'highlight_state' in settings.keys(): highlighted_series_doubling_time = [] length_hs = len(highlighted_series) - lag_days for i in range(length_hs): if highlighted_series[ i + lag_days] > 100 and highlighted_series[i] > 0: highlighted_series_doubling_time.append( 1 / (lag_days * np.log(2) / np.log(highlighted_series[i + lag_days] / highlighted_series[i]))) #Plot line of highlighted series doubling time history if len(highlighted_series_doubling_time) > 6: kwargs = { 'zorder': 2, 'color': highlight_color, 'lw': 1, 'markevery': [-7], 'ms': 2 } plt.plot( highlighted_series_doubling_time, highlighted_series[-len(highlighted_series_doubling_time):], '-o', **kwargs) hc_7 = True elif len(highlighted_series_doubling_time) > 1: kwargs = {'zorder': 2, 'color': highlight_color, 'lw': 1} plt.plot( highlighted_series_doubling_time, highlighted_series[-len(highlighted_series_doubling_time):], **kwargs) hc_7 = False else: hc_7 = False #Calculate US running doubling time length = len(total_count) - lag_days total_running_doubling_time = [] total_rp_running_doubling_time = [] for i in range(length): if total_count[i + lag_days] > 100: total_running_doubling_time.append( 1 / (lag_days * np.log(2) / np.log(total_count[i + lag_days] / total_count[i]))) total_rp_running_doubling_time.append( 1 / (lag_days * np.log(2) / np.log(total_count_rp[i + lag_days] / total_count_rp[i]))) #Plot total count if plot_total == True: total_doubling_time = lag_days * np.log(2) / np.log( total_count[-1] / total_count[lag_index]) total_inverse_doubling_time = 1 / total_doubling_time total_color = 'k' total_doubling_title = f"{total_doubling_time:.1f}" total_count_title = f"{int(total_count[-1])}" kwargs = {'zorder': 5, 'color': total_color} plt.scatter(total_inverse_doubling_time, total_count[-1], **kwargs) kwargs = { 'zorder': 3, 'lw': 1, 'color': total_color, 'markevery': [-7], 'ms': 2 } plt.plot(total_running_doubling_time, total_count[-len(total_running_doubling_time):], "-o", **kwargs) #Store values useful for the plot. max_value = max(max_value, total_count[-1]) max_doubling = max( max_doubling, 1 / (1 * np.log(2) / np.log(total_count[-1] / total_count[-2]))) min_doubling = min( min_doubling, 1 / (1 * np.log(2) / np.log(total_count[-1] / total_count[-2]))) #Plot grid and legend plt.grid() legend_title = f"Calculated from change\nbetween {cases[key]['date'][lag_index]:%b %d} and {cases[key]['date'][-1]:%b %d}" #Blank entry for legend. if 'highlight_state' in settings.keys(): plt.plot( [], [], '-o', color=highlight_color, label= f"{highlight_key} & trend after 100 cases\n Time-{highlight_doubling} days, Total-{highlight_total}" ) if plot_total == True: plt.plot( [], [], '-o', label= f'US Total & trend\n Time-{total_doubling_title} days, Total-{int(total_count_title)}', color=total_color) ax.scatter([], [], color='white', label="Abbreviated States & Territories") dot_l = False if 'highlight_state' in settings.keys() and hc_7 == True: p_hc = plt.scatter([], [], color=highlight_color, s=2) if plot_total == True: p_tc = plt.scatter([], [], color=total_color, s=2) #print("hc,tc") dot_h = [(p_hc, p_tc)] dot_l = ["Small dots were 7 days ago"] else: #print("hc") dot_h = [(p_hc)] dot_l = ["Small dot was 7 days ago"] else: if plot_total == True: p_tc = plt.scatter([], [], color=total_color, s=2) #print("tc") dot_h = [(p_tc)] dot_l = ["Small dot was 7 days ago"] handles, labels = ax.get_legend_handles_labels() if dot_l: handles = handles + dot_h labels = labels + dot_l kwargs = {'loc': 2, 'prop': {'size': 8}} if plot_type == 'deaths': kwargs['loc'] = 1 plt.legend(handles, labels, title=legend_title, handler_map={ tuple: HandlerTuple(ndivide=None) }, **kwargs).set_zorder(51) #Format x-ticks xticks = [ 1 / -0.5, 1 / -1, 1 / -2, 1 / -3, 1 / -4, 1 / -5, 1 / -6, 1 / -7, 0, 1 / 7, 1 / 6, 1 / 5, 1 / 4, 1 / 3, 1 / 2, 1 / 1, 1 / 0.5 ] xtick_labels = [ "Halving\nEvery\nHalf-day", "Halving\nEvery\nDay", "Halving\nEvery\n2 Days", "Halving\nEvery\n3 Days", "Halving\nEvery\n4 Days", "Halving\nEvery\n5 Days", "Halving\nEvery\n6 Days", "Halving\nEvery\nWeek", "no\nchange", "Doubling\nEvery\nWeek", "Doubling\nEvery\n6 Days", "Doubling\nEvery\n5 Days", "Doubling\nEvery\n4 Days", "Doubling\nEvery\n3 Days", "Doubling\nEvery\n2 Days", "Doubling\nEvery\nDay", "Doubling\nEvery\nHalf-day" ] #Format x-axis if np.absolute(max_doubling) > np.absolute(min_doubling): left = -max_doubling - 0.1 right = max_doubling + 0.1 else: left = min_doubling - 0.1 right = -min_doubling + 0.1 if plot_type != 'active': left = 0 if right < 0.333 or (left == 0 and right < 0.5): xticks = xticks[:5] + xticks[7:10] + xticks[12:] xtick_labels = xtick_labels[:5] + xtick_labels[7:10] + xtick_labels[12:] elif right < 0.5 or (left == 0 and right < 1): xticks = xticks[:4] + xticks[7:10] + xticks[13:] xtick_labels = xtick_labels[:4] + xtick_labels[7:10] + xtick_labels[13:] elif right < 1 or (left == 0 and right < 2): xticks = xticks[:3] + xticks[7:10] + xticks[14:] xtick_labels = xtick_labels[:3] + xtick_labels[7:10] + xtick_labels[14:] elif right < 2 or (left == 0 and right >= 2): xticks = xticks[:3] + xticks[7:10] + xticks[14:] xtick_labels = xtick_labels[:3] + [ xtick_labels[7], "", xtick_labels[9] ] + xtick_labels[14:] else: xticks = xticks[:3] + xticks[8] + xticks[6:] xtick_labels = xtick_labels[:3] + [""] + xtick_labels[6:] ax.set_xticks(xticks) ax.set_xticklabels(xtick_labels) plt.xlim(left, right) #Add logarithmic y-scale if 'log_y' in settings.keys() and settings['log_y'] == True: plt.yscale('log') y_locs, y_labels = plt.yticks() for i, loc in enumerate(y_locs): if loc == 1.e+00: y_labels[i] = "1" elif loc == 1.e+01: y_labels[i] = "10" elif loc == 1.e+02: y_labels[i] = "100" elif loc == 1.e+03: y_labels[i] = "1K" elif loc == 1.e+04: y_labels[i] = "10K" elif loc == 1.e+05: y_labels[i] = "100K" elif loc == 1.e+06: y_labels[i] = "1M" elif loc == 1.e+07: y_labels[i] = "10M" elif loc == 1.e+08: y_labels[i] = "100M" elif loc == 1.e+09: y_labels[i] = "1B" elif loc == 1.e+10: y_labels[i] = "10B" plt.yticks(y_locs, y_labels) plt.ylim(bottom=1) if max_value < 10: plt.ylim(top=10) elif max_value < 100: plt.ylim(top=100) elif max_value < 1000: plt.ylim(top=1000) #1K elif max_value < 10000: plt.ylim(top=10000) elif max_value < 100000: plt.ylim(top=100000) elif max_value < 1000000: plt.ylim(top=1000000) #1M elif max_value < 10000000: plt.ylim(top=10000000) elif max_value < 100000000: plt.ylim(top=100000000) elif max_value < 1000000000: plt.ylim(top=1000000000) #1B elif max_value < 10000000000: plt.ylim(top=10000000000) #Plot title title_string = { 'confirmed': 'Doubling Time of Cumulative COVID-19 Confirmed Cases', 'deaths': 'Doubling Time of Cumulative COVID-19 Deaths', 'recovered': 'Doubling Time of Cumulative COVID-19 Recovered Cases', 'active': 'Doubling Time of Daily COVID-19 Active Cases', 'daily': 'Doubling Time of Daily COVID-19 New Cases', } add_title = "\n(Non-Repatriated Cases)" if include_repatriated == False else "" plt.title(f"{title_string.get(plot_type)} {add_title}", fontweight='bold', loc='left') if left == 0: xlabel_text = "<--slower increase\t\t\tfaster increase-->".expandtabs() else: xlabel_text = "<--faster decrease\t\t\tfaster increase-->".expandtabs() plt.xlabel(xlabel_text, fontweight='bold') plt.ylabel("Number of Cases", fontweight='bold') #Plot attribution plt.title( f'Data from Johns Hopkins CSSE\nPlot by Stephen Mullens @srmullens\nCode adapted from Tomer Burg @burgwx', loc='right', fontsize=6) if plot_type == "active": kwargs = { 'fontweight': 'bold', 'ha': 'right', 'va': 'top', 'fontsize': 8 } active_text = "\"Active\" cases = confirmed total - recovered - deaths" plt.text(0.99, 0.99, active_text, transform=ax.transAxes, **kwargs) #Show plot and close if save_image['setting'] == True: savepath = os.path.join(save_image['directory_path'], f"{plot_type}_doubling_us.png") plt.savefig(savepath, bbox_inches='tight') else: plt.show() plt.close() #Alert script is done print("Done!")
def plot_pose_3d(ax, bones, pred, tar=None, limb_id=None, colors=None, good_keypts=None, show_pred_always=False, show_gt_always=False, normalize=False, legend=False, axes=False): """ Plot 3D pose Parameters ---------- ax : matplotlib axes object bones : list of lists of integers Bones in skeleton. pred : n x 3 numpy array Positions for n joints. tar : n x 3 numpy array, optional Useful when comparing target to prediction. The default is None. limb_id : list of integers, optional Numbers represent which leg the joint belongs to. The default is None. colors : list of triples, optional Color assigned to bones for each leg. The default is None. good_keypts : n x 3 boolean array, optional Selectively plot keypoints where good_keypoints is 1. The default is None. show_pred_always : boolean, optional Ignore good_keypts for predictions. The default is False. show_gt_always : boolean, optional Ignore good_keypts for ground truth. The default is False. normalize : boolean, optional Center pose by mean. The defauls is False. legend : boolean, optional Show legend. The default is False. axes : boolean, optional Show axes. The default is False. Returns ------- None. """ assert pred.ndim == 2 pred = pred.copy() if normalize: #move points to origin pred_m = np.nanmedian(pred, axis=0, keepdims=True) pred -= pred_m if tar is not None: tar = tar.copy() tar -= pred_m G = nx.Graph() G.add_edges_from(bones) G.add_nodes_from(np.arange(pred.shape[0])) # if limb_id or colors are not provided, then paint everything in blue if limb_id is None or colors is None: edge_colors = [[0, 0, 1.0] for _ in limb_id] else: edge_colors = [[x / 255.0 for x in colors[i]] for i in limb_id] plot_3d_graph( G, pred, ax, color_edge=edge_colors, style="--" if tar is not None else "-", good_keypts=good_keypts if not show_pred_always else None, ) if tar is not None: plot_3d_graph( G, tar, ax, color_edge=edge_colors, good_keypts=good_keypts if not show_gt_always else None, ) #### this bit is just to make special legend pts = np.nanmean(pred, axis=0) (p1, ) = ax.plot(pts[[0]], pts[[1]], pts[[2]], "b-", dashes=(2, 2)) p2, = ax.plot(pts, pts, pts, 'r-', dashes=(2, 2)) (p3, ) = ax.plot(pts[[0]], pts[[1]], pts[[2]], "b-") p4, = ax.plot(pts, pts, pts, 'r-') if legend: ax.legend( # [(p1), (p3)], [(p1, p2), (p3, p4)], ["LiftPose3D prediction", "Triangulated 3D pose"] if tar is not None else ["LiftPose3D prediction"], numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)}, loc=(0.1, 0.95), frameon=False, ) p1.remove() p3.remove() p2.remove() p4.remove() if not axes: ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_zticklabels([])