def plot_prediction(train_data, test_data, prediction, ax: matplotlib.axes.Axes = None) -> matplotlib.axes.Axes: """Plots case counts as step line, with outbreaks and alarms indicated by triangles.""" whole_data = pd.concat((train_data, test_data), sort=False) fontsize = 20 if ax is None: fig, ax = plt.subplots(figsize=(12, 8)) ax.step( x=whole_data.index, y=whole_data.n_cases, where="mid", color="blue", label="_nolegend_", ) alarms = prediction.query("alarm == 1") ax.plot(alarms.index, [0] * len(alarms), "g^", label="alarm", markersize=12) outbreaks = test_data.query("outbreak") ax.plot( outbreaks.index, outbreaks.n_outbreak_cases, "rv", label="outbreak", markersize=12, ) ax.set_xlabel("time", fontsize=fontsize) ax.set_ylabel("cases", fontsize=fontsize) ax.legend(fontsize="xx-large") return ax
def _apply_labels_mpl(self, ax: matplotlib.axes.Axes) -> None: if self.title is not None: ax.set_title(self.title) if self.x_label is not None: ax.set_xlabel(self.x_label) if self.y_label is not None: ax.set_ylabel(self.y_label)
def volcano_plot(df: pd.DataFrame, ax: matplotlib.axes.Axes) -> matplotlib.axes.Axes: '''Generate a volcano plot Parameters ---------- df : pd.DataFrame differential expression output from `diffex_multifactor`. ax : matplotlib.axes.Axes Returns ------- matplotlib.axes.Axes ''' if 'significant' not in df.columns: print('Adding significance cutoff at alpha=0.05') df['significant'] = df['q_val'] < 0.05 n_colors = len(np.unique(df['significant'])) sns.scatterplot(data=df, x='log2_fc', y='nlogq', hue='significant', linewidth=0., alpha=0.3, ax=ax, palette=sns.hls_palette(n_colors)[::-1]) ax.set_xlim((-6, 6)) ax.set_ylabel(r'$-\log_{10}$ q-value') ax.set_xlabel(r'$\log_2$ (Old / Young)') ax.get_legend().remove() return ax
def _rescale_ticks_and_units(ax: matplotlib.axes.Axes, data: List[Dict[str, Any]], cax: matplotlib.colorbar.Colorbar = None): """ Rescale ticks and units for the provided axes as described in :meth:`~_make_rescaled_ticks_and_units` """ # for x axis x_ticks_formatter, new_x_label = _make_rescaled_ticks_and_units(data[0]) if x_ticks_formatter is not None and new_x_label is not None: ax.xaxis.set_major_formatter(x_ticks_formatter) ax.set_xlabel(new_x_label) # for y axis y_ticks_formatter, new_y_label = _make_rescaled_ticks_and_units(data[1]) if y_ticks_formatter is not None and new_y_label is not None: ax.yaxis.set_major_formatter(y_ticks_formatter) ax.set_ylabel(new_y_label) # for z aka colorbar axis if cax is not None and len(data) > 2: z_ticks_formatter, new_z_label = _make_rescaled_ticks_and_units( data[2]) if z_ticks_formatter is not None and new_z_label is not None: cax.set_label(new_z_label) cax.formatter = z_ticks_formatter cax.update_ticks()
def plot_histogram(data_numpy: np.ndarray, xlabel: str, bins: str = 40, label: str = None, color: str = 'grey', ax: matplotlib.axes.Axes = None): """ Visualizes data as a histogram Parameters: data_numpy (numpy.ndarray): numpy ndarray of shape Nx1 xlabel (str): text that is displayed under the x axis bins (int): number of bins in the histogram (default 40) label (str): title of the histogram (default None) color (str): color of the barplot ax (matplotlib.axes.Axes): Axes to be used for plotting (default: create new) Returns: None """ if ax == None: ax = plt.gca() ax.hist(data_numpy, bins=bins, color=color, label=label) ax.set_yticks([]) ax.set_ylabel("Frequency") ax.set_xlabel(xlabel) ax.tick_params(left=False, bottom=False)
def _explained_variance_plot(model, ax: mpl.axes.Axes, cutoff: float = 0.9): n = len(model.explained_variance_ratio_) _x = np.arange(1, n + 1) _ycum = np.cumsum(model.explained_variance_ratio_) best_index = np.where(_ycum > cutoff)[0] # modify in case we dont have one best_index = best_index[0] if best_index.shape[0] > 0 else n - 1 # calculate AUC auc = np.trapz(_ycum, _x / n) # plot ax.plot(_x, _ycum, "x-") # plot best point ax.scatter( [_x[best_index]], [_ycum[best_index]], facecolors="None", edgecolors="red", s=100, label="n=%d, auc=%.3f" % (_x[best_index], auc), ) # plot 0 to 1 line ax.plot([1, n], [0, 1], "k--") ax.set_xlabel("N\n(Best proportion: %.3f)" % (_x[best_index] / (n + 1))) ax.set_ylabel("Explained variance (ratio)\n(cutoff=%.2f)" % cutoff) ax.grid() ax.legend()
def plot_2pcf(ax: matplotlib.axes.Axes, dr: np.ndarray, xi0: np.ndarray, xi1: np.ndarray) -> None: """ Plot the two-point correlation function for the x- and y-components of the astrometric residual field as a function of distance between points. Parameters ---------- ax: Matplotlib axis in which to plot dr: separations at which the 2-point correlation functions were calculated xi0: 2-point correlation function of the x-component of the astrometric residual field xi1: 2-point correlation function of the y-component of the astrometric residual field Returns ------- None """ # Plot the two-point correlation functions as a function of distance ax.axhline(y=0, ls='--', lw=1, c='gray') ax.plot(dr, xi0, marker='o', ms=5, ls='-', lw=1, label=r'$\xi_{xx}$') ax.plot(dr, xi1, marker='o', ms=5, ls='-', lw=1, label=r'$\xi_{yy}$') ax.legend() ax.set_xlabel(r'$\Delta$ [degrees]', fontsize=12) ax.set_ylabel(r'$\xi(\Delta)$ [degrees$^2$]', fontsize=12)
def plot_shots_per_exposure_compensation_setting(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None: """ Barplot of the number of shots per Exposure Compensation setting, on the provided subplot. Acts in place. Args: subplot: the subplot plt.axes on which to plot. data: the pandas DataFrame with your exif data. Returns: Nothing, plots in place. """ logger.debug("Plotting shots per exposure compensation setting") sns.countplot( x="Exposure_Compensation", hue=None, palette="pastel", data=data, ax=subplot, # order=data.Exposure_Compensation.value_counts().index, ) subplot.set_title("Number of Shots per Exposure Compensation Setting", fontsize=25) subplot.tick_params(axis="both", which="major", labelsize=13) subplot.set_xlabel("Exposure Compensation", fontsize=20) subplot.set_ylabel("Number of Shots", fontsize=20)
def _rescale_ticks_and_units( ax: matplotlib.axes.Axes, data: Sequence[DSPlotData], cax: matplotlib.colorbar.Colorbar = None, ) -> None: """ Rescale ticks and units for the provided axes as described in :func:`~_make_rescaled_ticks_and_units` """ # for x axis if not _is_string_valued_array(data[0]['data']): x_ticks_formatter, new_x_label = \ _make_rescaled_ticks_and_units(data[0]) ax.xaxis.set_major_formatter(x_ticks_formatter) ax.set_xlabel(new_x_label) # for y axis if not _is_string_valued_array(data[1]['data']): y_ticks_formatter, new_y_label = \ _make_rescaled_ticks_and_units(data[1]) ax.yaxis.set_major_formatter(y_ticks_formatter) ax.set_ylabel(new_y_label) # for z aka colorbar axis if cax is not None and len(data) > 2: if not _is_string_valued_array(data[2]['data']): z_ticks_formatter, new_z_label = \ _make_rescaled_ticks_and_units(data[2]) cax.set_label(new_z_label) cax.formatter = z_ticks_formatter cax.update_ticks()
def plot_shots_per_white_balance_setting(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None: """ Barplot of the number of shots per white balance setting, on the provided subplot. Acts in place. Args: subplot: the subplot plt.axes on which to plot. data: the pandas DataFrame with your exif data. Returns: Nothing, plots in place. """ logger.debug("Plotting shots per white balance setting") sns.countplot( y="White_Balance", hue=None, palette="pastel", data=data, ax=subplot, order=data.White_Balance.value_counts().index, ) subplot.set_title("Number of Shots per White Balance Setting", fontsize=25) subplot.tick_params(axis="both", which="major", labelsize=13) subplot.set_xlabel("Number of Shots", fontsize=20) subplot.set_ylabel("White Balance", fontsize=20)
def plot_shots_per_metering_mode(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None: """ Barplot of the number of shots per metering mode, on the provided subplot. Acts in place. Args: subplot: the subplot plt.axes on which to plot. data: the pandas DataFrame with your exif data. Returns: Nothing, plots in place. """ logger.debug("Plotting shots per metering mode") sns.countplot( x="Metering_Mode", hue=None, palette="pastel", data=data, ax=subplot, order=data.Metering_Mode.value_counts().index, ) subplot.set_title("Number of Shots per Metering Mode", fontsize=25) subplot.tick_params(axis="both", which="major", labelsize=13) # subplot.tick_params(axis="x", rotation=45) subplot.set_xlabel("Metering Mode", fontsize=20) subplot.set_ylabel("Number of Shots", fontsize=20)
def plot_shots_per_camera(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None: """ Barplot of the number of shots per camera, on the provided subplot. Acts in place. Args: subplot: the subplot matplotlib.axes.Axes on which to plot. data: the pandas DataFrame with your exif data. Returns: Nothing, plots in place. ??? warning "There is a danger here" Here is an explanation of the danger. Here is how to bypass it :) """ logger.debug("Plotting shots per camera") sns.countplot(y="Camera", hue="Brand", data=data, ax=subplot, order=data.Camera.value_counts().index) subplot.set_title("Number of Shots per Camera Model", fontsize=25) subplot.tick_params(axis="both", which="major", labelsize=13) subplot.set_xlabel("Number of Shots", fontsize=20) subplot.set_ylabel("Camera Model", fontsize=20) subplot.legend(loc="lower right", fontsize=18, title_fontsize=22)
def plot_shots_per_focal_length(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None: """ Barplot of the number of shots per focal length (FF equivalent), on the provided subplot. Args: subplot: the subplot matplotlib.axes.Axes on which to plot. data: the pandas DataFrame with your exif data. Returns: Nothing, plots in place. """ logger.debug("Plotting shots per focal length") sns.countplot( x="Focal_Range", hue="Lens", data=data, ax=subplot, order=data.Focal_Range.value_counts().index, ) subplot.set_title("Number of shots per Focal Length (FF equivalent)", fontsize=25) subplot.tick_params(axis="both", which="major", labelsize=13) subplot.set_xlabel("Focal Length", fontsize=20) subplot.set_ylabel("Number of Shots", fontsize=20) subplot.legend(loc="upper center", fontsize=15, title_fontsize=21)
def update_xlabel(ax: matplotlib.axes.Axes, xlabel_text: str, font_size: float = 12, font_weight: str = 'bold') -> None: """Set and stylize y-label.""" ax.set_xlabel(xlabel_text, fontdict=dict(fontsize=font_size, fontweight=font_weight), labelpad=2)
def _set_data_axes_labels(ax: matplotlib.axes.Axes, data: List[Dict[str, Any]], cax: Optional[matplotlib.colorbar.Colorbar]=None ) -> None: ax.set_xlabel(_make_label_for_data_axis(data, 0)) ax.set_ylabel(_make_label_for_data_axis(data, 1)) if cax is not None and len(data) > 2: cax.set_label(_make_label_for_data_axis(data, 2))
def _draw(self, ax: mpl.axes.Axes, plot_timestamps: np.ndarray, date_formatter: Optional[DateFormatter]) -> None: if self.time_plot: self._reindex(plot_timestamps) if date_formatter is not None: ax.xaxis.set_major_formatter(date_formatter) lines = [] ax2 = None if self.secondary_y is not None and len(self.secondary_y): ax2 = ax.twinx() for data in self.data_list: if _VERBOSE: print(f'plotting data: {data.name}') if ax2 and data.name in self.secondary_y: line = _plot_data(ax2, data) else: line = _plot_data(ax, data) lines.append(line) for date_line in self.date_lines: # vertical lines on time plot line = draw_date_line(ax, plot_timestamps, date_line.date, date_line.line_type, date_line.color) if date_line.name is not None: lines.append(line) for horizontal_line in self.horizontal_lines: line = draw_horizontal_line(ax, horizontal_line.y, horizontal_line.line_type, horizontal_line.color) if horizontal_line.name is not None: lines.append(line) for vertical_line in self.vertical_lines: line = draw_vertical_line(ax, vertical_line.x, vertical_line.line_type, vertical_line.color) if vertical_line.name is not None: lines.append(line) self.legend_names = [data.name for data in self.data_list] self.legend_names += [date_line.name for date_line in self.date_lines if date_line.name is not None] self.legend_names += [horizontal_line.name for horizontal_line in self.horizontal_lines if horizontal_line.name is not None] self.legend_names += [vertical_line.name for vertical_line in self.vertical_lines if vertical_line.name is not None] if self.ylim: ax.set_ylim(self.ylim) if (len(self.data_list) > 1 or len(self.date_lines)) and self.display_legend: ax.legend([line for line in lines if line is not None], [self.legend_names[i] for i, line in enumerate(lines) if line is not None], loc=self.legend_loc) if self.log_y: ax.set_yscale('log') ax.yaxis.set_major_locator(mtick.AutoLocator()) ax.yaxis.set_minor_locator(mtick.NullLocator()) if self.y_tick_format: ax.yaxis.set_major_formatter(mtick.StrMethodFormatter(self.y_tick_format)) if self.title: ax.set_title(self.title) if self.xlabel: ax.set_xlabel(self.xlabel) if self.ylabel: ax.set_ylabel(self.ylabel) if self.zlabel: ax.set_zlabel(self.zlabel) ax.relim() ax.autoscale_view()
def _set_data_axes_labels( ax: matplotlib.axes.Axes, data: Sequence[DSPlotData], cax: Optional[matplotlib.colorbar.Colorbar] = None, ) -> None: ax.set_xlabel(_make_label_for_data_axis(data, 0)) ax.set_ylabel(_make_label_for_data_axis(data, 1)) if cax is not None and len(data) > 2: cax.set_label(_make_label_for_data_axis(data, 2))
def plot_sensor_hit_histogram(axes: mpl.axes.Axes, hist: np.ndarray, x_edges: np.ndarray, y_edges: np.ndarray): """ plot the hitmap of the sensor into a given axes . plots the hitmap of the sensor into a provided axes instance and annotates the plot accordingly """ cmap = cm.get_cmap('viridis', 1024) axes.set_title("Sensor Hitmap") axes.set_xlabel("x [mm]") axes.set_ylabel("y [mm]") axes.pcolormesh(x_edges, y_edges, hist, cmap=cmap)
def customize_ax(ax: matplotlib.axes.Axes, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, invert_yaxis=False, xticks_maj_freq=None, xticks_min_freq=None, yticks_maj_freq=None, yticks_min_freq=None, with_hline=False, hline_height=None, hline_color='r', hline_style='--'): """ : ax (matplotlib.axes.Axes): plot to customize. : Use to customize a plot with labels, ticks, etc. """ if xlabel is not None: ax.set_xlabel(xlabel) if ylabel is not None: ax.set_ylabel(ylabel) if xlim is not None: ax.set_xlim(xlim) if ylim is not None: ax.set_ylim(ylim) if invert_yaxis: ax.invert_yaxis() if title is not None: ax.set_title(title) if xticks_maj_freq is not None: ax.xaxis.set_major_locator(ticker.MultipleLocator(xticks_maj_freq)) if xticks_min_freq is not None: ax.xaxis.set_minor_locator(ticker.MultipleLocator(xticks_min_freq)) if yticks_maj_freq is not None: ax.yaxis.set_major_locator(ticker.MultipleLocator(yticks_maj_freq)) if yticks_min_freq is not None: ax.yaxis.set_minor_locator(ticker.MultipleLocator(yticks_min_freq)) if with_hline: if hline_height is None: ylim = plt.ylim() hline_height = max(ylim) / 2 ax.axhline(y=hline_height, color=hline_color, linestyle=hline_style)
def plot_and_label_1d_signal_and_background_with_matplotlib_on_axis(ax: matplotlib.axes.Axes, jet_hadron: "correlations.Correlations", apply_correlation_scale_factor: bool = True) -> None: """ Plot and label the signal and background dominated hists on the given axis. This is a helper function so that we don't have to repeat code when we need to plot these hists. It can also be used in other modules. Args: ax: Axis on which the histograms should be plotted. jet_hadron: Correlations object from which the delta_phi hists should be retrieved. apply_correlation_scale_factor: Whether to scale the histogram by the correlation scale factor. Returns: None. The given axis is modified. """ # Setup hists = jet_hadron.correlation_hists_delta_phi h_signal = histogram.Histogram1D.from_existing_hist(hists.signal_dominated.hist) if apply_correlation_scale_factor: h_signal *= jet_hadron.correlation_scale_factor ax.errorbar( h_signal.x, h_signal.y, yerr = h_signal.errors, label = hists.signal_dominated.type.display_str(), marker = "o", linestyle = "", ) h_background = histogram.Histogram1D.from_existing_hist(hists.background_dominated.hist) if apply_correlation_scale_factor: h_background *= jet_hadron.correlation_scale_factor # Plot with opacity first background_plot = ax.errorbar( h_background.x, h_background.y, yerr = h_background.errors, marker = "o", linestyle = "", alpha = 0.5, ) # Then restrict range and plot without opacity near_side = len(h_background.x) // 2 ax.errorbar( h_background.x[:near_side], h_background.y[:near_side], yerr = h_background.errors[:near_side], label = hists.background_dominated.type.display_str(), marker = "o", linestyle = "", color = background_plot[0].get_color() ) # Set labels. ax.set_xlabel(labels.make_valid_latex_string(hists.signal_dominated.hist.GetXaxis().GetTitle())) ax.set_ylabel(labels.make_valid_latex_string(hists.signal_dominated.hist.GetYaxis().GetTitle())) jet_pt_label = labels.jet_pt_range_string(jet_hadron.jet_pt) track_pt_label = labels.track_pt_range_string(jet_hadron.track_pt) ax.set_title(fr"Unsubtracted 1D ${hists.signal_dominated.axis.display_str()}$," f" {jet_hadron.reaction_plane_orientation.display_str()} event plane orient.," f" {jet_pt_label}, {track_pt_label}")
def plot(self, ax: matplotlib.axes.Axes): # individual points ax.scatter(self.mean, self.diff, s=20, alpha=0.6, color=self.color_points, **self.point_kws) # mean difference and SD lines ax.axhline(self.mean_diff, color=self.color_mean, linestyle='-') ax.axhline(self.mean_diff + self.loa_sd, color=self.color_loa, linestyle='--') ax.axhline(self.mean_diff - self.loa_sd, color=self.color_loa, linestyle='--') if self.reference: ax.axhline(0, color='grey', linestyle='-', alpha=0.4) # confidence intervals (if requested) if self.CI is not None: ax.axhspan(self.CI_mean[0], self.CI_mean[1], color=self.color_mean, alpha=0.2) ax.axhspan(self.CI_upper[0], self.CI_upper[1], color=self.color_loa, alpha=0.2) ax.axhspan(self.CI_lower[0], self.CI_lower[1], color=self.color_loa, alpha=0.2) # text in graph trans: matplotlib.transform = transforms.blended_transform_factory( ax.transAxes, ax.transData) offset: float = (((self.loa * self.sd_diff) * 2) / 100) * 1.2 ax.text(0.98, self.mean_diff + offset, 'Mean', ha="right", va="bottom", transform=trans) ax.text(0.98, self.mean_diff - offset, f'{self.mean_diff:.2f}', ha="right", va="top", transform=trans) ax.text(0.98, self.mean_diff + self.loa_sd + offset, f'+{self.loa:.2f} SD', ha="right", va="bottom", transform=trans) ax.text(0.98, self.mean_diff + self.loa_sd - offset, f'{self.mean_diff + self.loa_sd:.2f}', ha="right", va="top", transform=trans) ax.text(0.98, self.mean_diff - self.loa_sd - offset, f'-{self.loa:.2f} SD', ha="right", va="top", transform=trans) ax.text(0.98, self.mean_diff - self.loa_sd + offset, f'{self.mean_diff - self.loa_sd:.2f}', ha="right", va="bottom", transform=trans) # transform graphs ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # set X and Y limits if self.xlim is not None: ax.set_xlim(self.xlim[0], self.xlim[1]) if self.ylim is not None: ax.set_ylim(self.ylim[0], self.ylim[1]) # graph labels ax.set_ylabel(self.y_title) ax.set_xlabel(self.x_title) if self.graph_title is not None: ax.set_title(self.graph_title)
def plot_shots_per_iso_setting(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None: """ Barplot of the number of shots per ISO setting, on the provided subplot. Acts in place. Args: subplot: the subplot plt.axes on which to plot. data: the pandas DataFrame with your exif data. Returns: Nothing, plots in place. """ logger.debug("Plotting shots per ISO") sns.countplot(x="ISO", hue=None, data=data, ax=subplot) # order=data.ISO.value_counts().index) subplot.set_title("Number of Shots per ISO Setting", fontsize=25) subplot.tick_params(axis="both", which="major", labelsize=13) subplot.set_xlabel("ISO Value", fontsize=20) subplot.set_ylabel("Number of Shots", fontsize=20)
def plot_astrometric_residuals(ax: matplotlib.axes.Axes, xs: np.ndarray, ys: np.ndarray) -> None: """ Plot the astrometric residual field of a set of points. Parameters ---------- ax: Matplotlib axis in which to plot xs: Array of the x- and y-components of the field ys: Array of the x- and y-components of the astrometric residual field Returns ------- None """ qdict = dict( alpha=1, angles='uv', headlength=5, headwidth=3, headaxislength=4, minlength=0, pivot='middle', scale_units='xy', width=0.002, color='#001146' ) q = ax.quiver(xs[:, 0], xs[:, 1], ys[:, 0], ys[:, 1], scale=1, **qdict) ax.quiverkey(q, 0.0, 1.8, 0.1, 'residual = 0.1 arcsec', coordinates='data', labelpos='N', color='darkred', labelcolor='darkred') ax.set_xlabel('RA [degrees]') ax.set_ylabel('Dec [degrees]') ax.set_xlim(-1.95, 1.95) ax.set_ylim(-1.9, 2.0) ax.set_aspect('equal')
def plot_shots_per_fnumber(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None: """ Barplot of the number of shots per F number, on the provided subplot. Args: subplot: the subplot matplotlib.axes.Axes on which to plot. data: the pandas DataFrame with your exif data. Returns: Nothing, plots in place. """ logger.debug("Plotting shots per aperture number") sns.countplot(x="F_Number", data=data, ax=subplot) subplot.set_title("Distribution of Apertures", fontsize=25) subplot.tick_params(axis="both", which="major", labelsize=13) subplot.tick_params(axis="x", rotation=70) subplot.set_xlabel("F Number", fontsize=20) subplot.set_ylabel("Number of Shots", fontsize=20)
def plot_testcount_forecast( result: pandas.Series, m: preprocessing.fbprophet.Prophet, forecast: pandas.DataFrame, considered_holidays: preprocessing.NamedDates, *, ax: matplotlib.axes.Axes=None ) -> matplotlib.axes.Axes: """ Helper function for plotting the detailed testcount forecasting result. Parameters ---------- result : pandas.Series the date-indexed series of smoothed/predicted testcounts m : fbprophet.Prophet the prophet model forecast : pandas.DataFrame contains the prophet model prediction holidays : dict of { datetime : str } dictionary of the holidays that were used in the model ax : optional, matplotlib.axes.Axes an existing subplot to use Returns ------- ax : matplotlib.axes.Axes the (created) subplot that was plotted into """ if not ax: _, ax = pyplot.subplots(figsize=(13.4, 6)) m.plot(forecast[forecast.ds >= m.history.set_index('ds').index[0]], ax=ax) ax.set_ylim(bottom=0) ax.set_xlim(pandas.to_datetime('2020-03-01')) plot_vlines(ax, considered_holidays, alignment='bottom') ax.legend(frameon=False, loc='upper left', handles=[ ax.scatter([], [], color='black', label='training data'), ax.plot([], [], color='blue', label='prediction')[0], ax.plot(result.index, result.values, color='orange', label='result')[0], ]) ax.set_ylabel('total tests') ax.set_xlabel('') return ax
def plot_shots_per_shutter_speed(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None: """ Barplot of the number of shots per shutter speed, on the provided subplot. Acts in place. Args: subplot: the subplot plt.axes on which to plot. data: the pandas DataFrame with your exif data. Returns: Nothing, plots in place. """ logger.debug("Plotting shots per shutter speed") sns.countplot(x="Shutter_Speed", data=data, ax=subplot, order=data.Shutter_Speed.value_counts().index) subplot.set_title("Number of Shots per Shutter Speed", fontsize=25) subplot.tick_params(axis="x", which="major", rotation=70) subplot.set_xlabel("Shutter Speed", fontsize=20) subplot.set_ylabel("Number of Shots", fontsize=20)
def plot_model_probabilities( history: History, rotation: int = 0, title: str = "Model probabilities", ax: mpl.axes.Axes = None, ): """ Plot the probabilities of models over time. Parameters ---------- history: History The history to extract data from. rotation: int, optional (default = 0) Rotation of x axis labels. title: str, optional Title of the plot. ax: matplotlib.axes.Axes, optional The axis object to use. """ # create figure if ax is None: _, ax = plt.subplots() # extract model probabilities model_probabilities = history.get_model_probabilities() # displayed in plot legend model_probabilities.columns.name = "Model" # plot ax = model_probabilities.plot.bar(rot=rotation, legend=True, ax=ax) # format plot ax.set_ylabel("Probability") ax.set_xlabel("Population index") ax.set_title(title) return ax
def heatmap(values: List[float], ax: mpl.axes.Axes) -> mpl.axes.Axes: """ Plot a seaborn heatmap Args: values (List[float]): list of values in the following order: * true positives * false negatives * false positives * true negatives """ mf = pd.DataFrame(np.array(values).reshape(2, 2)) mf.columns, mf.index = ['True', 'False'], ['True', 'False'] sns.heatmap(mf, annot=True, cmap='Blues', fmt='g', ax=ax) ax.set_xlabel('Predicted') ax.set_ylabel('Ground Truth') return ax
def plot_scatter(ax: mpl.axes.Axes, accuracy_samples: np.ndarray, ece_samples: np.ndarray, limit=5, plot_kwargs: Dict[str, Any] = {}) -> mpl.axes.Axes: _plot_kwargs = DEFAULT_PLOT_KWARGS.copy() _plot_kwargs.update(plot_kwargs) # plot x = np.mean(accuracy_samples, axis=1) y = np.mean(ece_samples, axis=1) xerr = np.std(accuracy_samples, axis=1) yerr = np.std(ece_samples, axis=1) # most accuracy top k idx = x.argsort()[-limit:][::-1] ax.errorbar(x[idx], y[idx], xerr=xerr[idx], yerr=yerr[idx], fmt='o', alpha=0.8, color='b', **_plot_kwargs) # least accuracy top k idx = x.argsort()[:limit] ax.errorbar(x[idx], y[idx], xerr=xerr[idx], yerr=yerr[idx], fmt='o', alpha=0.8, color='r', **_plot_kwargs) # other predicted classes idx = x.argsort()[limit:-limit] ax.errorbar(x[idx], y[idx], xerr=xerr[idx], yerr=yerr[idx], fmt='o', alpha=0.2, color='k', **_plot_kwargs) ax.set_xlabel('Accuracy') # ax.set_ylabel('ECE') return ax
def plot_shots_per_lens(subplot: matplotlib.axes.Axes, data: pd.DataFrame) -> None: """ Barplot of the number of shots per lens used, on the provided subplot. Acts in place. Args: subplot: the subplot plt.axes on which to plot. data: the pandas DataFrame with your exif data. Returns: Nothing, plots in place. """ logger.debug("Plotting shots per lens") sns.countplot(y="Lens", hue="Brand", data=data, ax=subplot, order=data.Lens.value_counts().index) subplot.set_title("Number of Shots per Lens Model", fontsize=25) subplot.tick_params(axis="both", which="major", labelsize=13) subplot.set_xlabel("Number of Shots", fontsize=20) subplot.set_ylabel("Lens Model", fontsize=20) subplot.legend(loc="lower right", fontsize=18, title_fontsize=25)
def plot_misses_against_hits(ax: mpl.axes.Axes, x: Sequence[int], y: Sequence[int], **kwargs) -> mpl.collections.PathCollection: ax.set_xlabel("Cache misses") ax.set_ylabel("Cache hits") return ax.scatter(x, y, edgecolors="none", **kwargs)