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_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 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 company_distribution(df: pd.DataFrame, ax: mp.axes.Axes) -> ResultValue: log = logging.getLogger('company_distribution') log.info(" >>") try: def autopct_format(values): def my_format(pct): total = sum(values) val = int(round(pct * total / 100.0)) str_val = f'{val:n}' return '{v:d}'.format(v=val) return my_format colors = [ "#9aff33", "#34ff33", "#33ff98", "#33fffe", "#339aff", "#3371ff", "#5b33ff", "#c133ff", "#ff33d7" ] by_company = df.groupby(["fornitore"]).sum() by_company.reset_index(level=0, inplace=True) values = by_company["numero_dosi"] labels = by_company["fornitore"] ax.pie(values, labels=labels, colors=colors, autopct=autopct_format(values)) ax.set_title("Vaccini consegnati", fontsize=18) except Exception as ex: log.error("Exception caught - {ex}".format(ex=ex)) return ResultKo(ex) log.info(" <<") return ResultOk(True)
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 contour_transition(da_transition: xr.DataArray, ax: mpl.axes.Axes, rcp: str): """Takes in DataArray for transition time from x to y months Omega Aragonite undersaturation, axes for the plot, and the simulation name, and makes a contour plot.""" crs = ccrs.Robinson(central_longitude=180) src = ccrs.PlateCarree() clevs = np.arange(0, 31, 5) lon = da_transition.xt_ocean.data lat = da_transition.yt_ocean.data im = ax.contourf(lon, lat, da_transition, cmap='plasma', levels=clevs, transform=src, robust=True) if ax == plt.gcf().get_axes()[0]: cbar = plt.colorbar(im, ax=plt.gcf().get_axes(), orientation='horizontal', fraction=0.05, pad=0.05) cbar.set_label( 'Transition Time from 1-->6 Months Undersaturated (years)', fontsize=16) ax.add_feature(cfeature.LAND, zorder=10, facecolor='darkgray') ax.set_global() ax.set_title(rcp)
def age_distribution(df: pd.DataFrame, ax: mp.axes.Axes, gender: str = "F") -> ResultValue: log = logging.getLogger('age_distribution') log.info(" >>") try: if gender.upper() not in ["M", "F", "B"]: msg = "Geneder {v} value not known".format(v=gender) log.error(msg) return ResultKo(Exception(msg)) by_age = df.groupby(["fascia_anagrafica"]).sum() by_age.reset_index(level=0, inplace=True) by_age["totals"] = by_age["sesso_femminile"] + by_age["sesso_maschile"] values = by_age["sesso_femminile" if gender == "F" else ("sesso_maschile" if gender == "M" else "totals")] labels = by_age["fascia_anagrafica"] ax.pie(values, labels=labels, autopct='%1.1f%%', colors=colors) ax.set_title("Distribuzione per eta'", fontsize=18) except Exception as ex: log.error("Exception caught - {ex}".format(ex=ex)) return ResultKo(ex) log.info(" <<") return ResultOk(True)
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 _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 update_title(ax: matplotlib.axes.Axes, title_text: str, font_size: float = 12, font_weight: str = 'bold', pad: float = -8) -> None: """Set and stylize title.""" ax.set_title(title_text, fontdict=dict(fontsize=font_size, fontweight=font_weight), pad=pad)
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 plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None: """ Draw plot on ax back_color: background color for plot """ ax.ticklabel_format(axis="y", scilimits=[0, 0]) ax.set_facecolor(back_color) ax.set_title(f"{self.title}\n{self.group_name}")
def show_4d_images(fig: matplotlib.figure.Figure, ax: matplotlib.axes.Axes, image: np.array, est_cor_idx: list = None, img_name: str = None): """ Lists all the files given a root folder. Args: fig (matplotlib.figure.Figure): Figure object ax (matplotlib.axes.Axes): Axes object image (np.array): 4D image tensor to be shown est_cor_idx (list): List containing the percentage of corruption for each time and z-axes. """ assert len(image.shape) == 4, "Image's tensor rank is {}, not 4".format( len(image.shape)) axcolor = 'lightgoldenrodyellow' axz = plt.axes([0.15, 0.05, 0.65, 0.03], facecolor=axcolor) axt = plt.axes([0.15, 0.10, 0.65, 0.03], facecolor=axcolor) zpos = Slider(axz, 'Z Axis', 1, image.shape[-2], valfmt="%d") tpos = Slider(axt, 'Time Axis', 1, image.shape[-1], valfmt="%d") pos_z = 0 pos_t = 0 im = ax.imshow(image[:, :, pos_z, pos_t]) if est_cor_idx: ax.set_title("ID: " + img_name + " Estimated Corruption: {:.5}".format(str(est_cor_idx))) else: ax.set_title("ID: " + img_name) def update(val): pos_z = int(zpos.val) pos_t = int(tpos.val) fig.canvas.draw_idle() im.set_data(image[:, :, pos_z - 1, pos_t - 1]) if est_cor_idx: ax.set_title( "ID: " + img_name + " Estimated Corruption: {:.5}".format(str(est_cor_idx))) else: ax.set_title("ID: " + img_name) zpos.on_changed(update) tpos.on_changed(update) plt.show()
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 post_process_plt(df: pd.DataFrame, ax: plt.axes.Axes, percent: bool = False) -> plt.figure.Figure: """Post-process the Matplotlib Axes instance produced by :func:`pre_process_plt`. The post-processing invovles further formatting of the legend, the x-axis and the y-axis. Parameters ---------- df : :class:`pandas.DataFrame` A DataFrame holding the accumulated SBU usage. See :func:`pre_process_df` and :func:`.get_agregated_sbu`. ax : :class:`matplotlib.Axes<matplotlib.axes.Axes>` An Axes instance produced by :func:`pre_process_plt`. percent : class`bool` If ``True``, apply additional formatting for handling percentages. Returns ------- :class:`matplotlib.figure.Figure`: A Matplotlib Figure constructed from **ax**. """ df_max = df.max().max() decimals = 1 - len(str(int(df.values.max()))) y_max = round(df_max, decimals) + 10**-decimals # Format the y-axis ax.yaxis.set_major_formatter(plt.ticker.StrMethodFormatter('{x:,.0f}')) ax.set(ylim=(0, y_max)) # Format the x-axis i = len(df.index) // 6 or 1 ax.set(xticks=df.index[0::i]) today = date.today().strftime('%d %b %Y') if percent: ax.set_ylabel('SBUs (System Billing Units) / %') ax.set_title('Accumulated % SBU usage: {}'.format(today), fontdict={'fontsize': 18}) ax.legend_.set_title('Project (PI): % SBU') else: ax.set_ylabel('SBUs (System Billing Units) / hours') ax.set_title('Accumulated SBU usage: {}'.format(today), fontdict={'fontsize': 18}) ax.legend_.set_title('Project (PI): SBU') return ax.get_figure()
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 display_segmented_image(y: np.ndarray, threshold: float = 0.5, input_image: np.ndarray = None, alpha_input_image: float = 0.2, title: str = '', ax: matplotlib.axes.Axes = None) -> None: """Display segemented image. This function displays the image where each class is shown in particular color. This is useful for getting a rapid view of the performance of the model on a few examples. Parameters: y: The array containing the prediction. Must be of shape (image_shape, num_classes) threshold: The threshold used on the predictions. input_image: If provided, display the input image in black. alpha_input_image: If an input_image is provided, the transparency of the input_image. """ ax = ax or plt.gca() base_array = np.ones((y.shape[0], y.shape[1], 3)) * 1 legend_handles = [] for i in range(y.shape[-1]): # Retrieve a color (without the transparency value). colour = plt.cm.jet(i / y.shape[-1])[:-1] base_array[y[..., i] > threshold] = colour legend_handles.append(mpatches.Patch(color=colour, label=str(i))) # plt.figure(figsize=figsize) ax.imshow(base_array) ax.legend(handles=legend_handles, bbox_to_anchor=(1, 1), loc='upper left') ax.set_yticks([]) ax.set_xticks([]) ax.set_title(title) if input_image is not None: ax.imshow(input_image[..., 0], cmap=plt.cm.binary, alpha=alpha_input_image) if not ax: plt.show()
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_step_analyzer(axes: matplotlib.axes.Axes, result: dict, title: str, legends: list, colorset: int): colors = [ ('red', 'green', 'blue'), # TODO: add more colors ('tomato', 'lightgreen', 'steelblue'), ] c = colors[colorset] n = len(result['states']) for i in range(n): if legends: axes.plot(result['times'], result['states'][i], color=c[i], label=legends[i]) else: axes.plot(result['times'], result['states'][i], color=c[i]) if result['references'][i] != 0.0: axes.axhline(result['references'][i], linestyle='--', color=c[i]) axes.axhline(result['references'][i] - result['thresholds'][i], linestyle='-.', color=c[i]) axes.axhline(result['references'][i] + result['thresholds'][i], linestyle='-.', color=c[i]) axes.axhline(result['references'][i] + result['overshoots'][i], linestyle=':', color=c[i]) if result['risetimes'][i] > 0.0: axes.axvline(result['risetimes'][i], linestyle='--', color=c[i]) if result['settletimes'][i] > 0.0: axes.axvline(result['settletimes'][i], linestyle='-.', color=c[i]) if legends: axes.legend() if title: axes.set_title(title) axes.set_xlim(result['times'][0], result['times'][-1]) axes.figure.tight_layout()
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 contour_temp(ds: xr.core.dataset.Dataset, in_year: int, ax: mpl.axes.Axes, title: str, central_longitude: int = 0) -> mpl.axes.Axes: """Takes in a Dataset for Temperature, and creates a contour plot for the data for the given year. Adds a darkgrey landmask, grindlines, coastlines, a title, and a colorbar to the plot.""" clevs = np.arange(260, 320, 10) # Can also choose to define colormap colors = ['blue', 'green', 'yellow', 'orange', 'red'] crs = ccrs.PlateCarree(central_longitude=central_longitude) # Specify variables X = ds['xt_ocean'] Y = ds['yt_ocean'] # Already grouped by year Z = ds['temp'].sel(year=in_year).squeeze() Z, X = add_cyclic_point(Z, coord=X) # can also use cmap='plasma','inferno',etc... im = ax.contourf(X, Y, Z, levels=clevs, transform=crs) if ax == plt.gcf().get_axes()[0]: cbar = plt.colorbar(im, ax=plt.gcf().get_axes(), orientation='horizontal', fraction=0.05, pad=0.05) cbar.set_label('Temeprature ($^\circ\,K$)', fontsize=18) # Zoom in on a region # ax.set_extent([x0,x1,y0,y1]) # Add land mask, gridlines, coastlines, and title ax.add_feature(cfeature.LAND, zorder=10, facecolor='darkgray') ax.gridlines() ax.coastlines() ax.set_title(title + " " + str(in_year), fontsize=18, loc='center') 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 contour_oa(ds: xr.core.dataset.Dataset, in_year: int, ax: mpl.axes.Axes, title: str, central_longitude: int = 0) -> mpl.axes.Axes: """Takes in a Dataset for Omega Aragonite, and creates a contour plot for the data for the given year. Adds a darkgrey landmask, grindlines, coastlines, a title, and a colorbar to the plot.""" clevs = np.array([0, 1, 2, 3, 4]) # Can also choose to define colormap # colors = ['red', 'orange', 'yellow','green','blue'] crs = ccrs.PlateCarree(central_longitude=central_longitude) # Specify variables X = ds['XT_OCEAN'] Y = ds['YT_OCEAN'] # Already grouped by year Z = ds['OMEGA_ARAG'].sel(year=in_year).squeeze() Z, X = add_cyclic_point(Z, coord=X) im = ax.contourf(X, Y, Z, clevs, transform=crs) if ax == plt.gcf().get_axes()[0]: cbar = plt.colorbar(im, ax=plt.gcf().get_axes(), orientation='horizontal', fraction=0.05, pad=0.05) cbar.set_label('$\Omega$ Aragonite', fontsize=18) # Zoom in on a region # ax.set_extent([x0,x1,y0,y1]) # Add land mask, gridlines, coastlines, and title ax.add_feature(cfeature.LAND, zorder=10, facecolor='darkgray') ax.gridlines() ax.coastlines() ax.set_title(title + " " + str(in_year), fontsize=18, loc='center') return ax
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 plot_violin(ax: matplotlib.axes.Axes, violin_data: Sequence[float], markers: Sequence[AxisMarker], label: str, color: str = COLOR_LABEL) -> None: ax.set_title(label, fontdict={'fontsize': 14}, color=color) # plot violin graph violin_parts = ax.violinplot(violin_data, bw_method=0.07, showmedians=False, showextrema=False) # set violin background color for pc in violin_parts['bodies']: pc.set_facecolor(COLOR_BG) pc.set_edgecolor(COLOR_BG) # draw axis markers for marker in markers: marker.draw(ax) # turn off axis spines for sp in ['right', 'top', 'bottom']: ax.spines[sp].set_color('none') # move the left ax spine to center ax.spines['left'].set_position(('data', 1)) # customize axis ticks ax.xaxis.set_major_locator(matplotlib.ticker.NullLocator()) ax.xaxis.set_minor_locator(matplotlib.ticker.NullLocator()) if max(violin_data) == 0: # fix tick at 0 when there's no data ax.yaxis.set_major_locator(matplotlib.ticker.FixedLocator([0])) else: ax.yaxis.set_major_locator( matplotlib.ticker.MaxNLocator(nbins='auto', steps=[1, 2, 4, 5, 10], integer=True)) ax.yaxis.set_minor_locator(matplotlib.ticker.NullLocator()) ax.tick_params(labelsize=14)
def _add_properties(self, ax: matplotlib.axes.Axes, title: str = None, title_padding: float = None, save_path: str = None, filename: str = None, hide_axis: bool = False, tight_layout: bool = True): if tight_layout: plt.tight_layout() if hide_axis: ax.axis('off') if title is not None: ax.set_title(title, pad=title_padding, fontdict={'fontweight': 'bold'}) if save_path is not None and filename is not None: self._data_service.save_figure(save_path, filename, no_axis=False)
def chart_vaccinations_fornitore(df: pd.DataFrame, ax: mp.axes.Axes) -> ResultValue: log = logging.getLogger('chart_vaccinations_fornitore') log.info(" >>") try: by_company = df.groupby(["fornitore"]).sum() by_company["totals"] = by_company["sesso_maschile"] + by_company[ "sesso_femminile"] by_company.reset_index(level=0, inplace=True) values = by_company["totals"] labels = by_company["fornitore"] ax.pie(values, labels=labels, colors=["#dfeef4", "#c2e7f6", "#7fd2f3"], autopct='%1.1f%%') ax.set_title("Distribuzione per fornitore", fontsize=18) except Exception as ex: log.error("Exception caught - {ex}".format(ex=ex)) return ResultKo(ex) log.info(" <<") return ResultOk(True)
def chart_vaccinations_male_female(df: pd.DataFrame, ax: mp.axes.Axes) -> ResultValue: log = logging.getLogger('chart_vaccinations_male_female') log.info(" >>") try: num_male = df["sesso_maschile"].sum() num_female = df["sesso_femminile"].sum() parts = [num_female, num_male] labels = ["Donne", "Uomini"] female_color = "#f1a29b" male_color = "#9bd7f1" ax.pie(parts, labels=labels, colors=[female_color, male_color], autopct='%1.1f%%') ax.set_title("Distribuzione per genere", fontsize=18) except Exception as ex: log.error("Exception caught - {ex}".format(ex=ex)) return ResultKo(ex) log.info(" <<") return ResultOk(True)