def plot_positive_negative_bars(ax: plt.Axes, values: pd.Series, positive_dict: dict = None, negative_dict: dict = None, title='Significant Spearman Correlation', x_label='Spearman Correlation'): if positive_dict is None: positive_dict = {} if negative_dict is None: negative_dict = {} default_positive_dict = {'color': 'green', 'height': 0.8} default_negative_dict = {'color': 'red', 'height': 0.8} positive_dict = set_default_parameters(positive_dict, default_positive_dict) negative_dict = set_default_parameters(negative_dict, default_negative_dict) sorted_values = values.sort_values() y_position = np.arange(len(sorted_values)) positive_values = sorted_values.apply(lambda x: x if x >= 0 else 0) ax.barh(y_position, positive_values, **positive_dict) negative_values = sorted_values.apply(lambda x: x if x < 0 else 0) ax.barh(y_position, negative_values, **negative_dict) ax.set_yticks(y_position) ax.set_yticklabels(sorted_values.index, size=14) if title is not None: ax.set_title(title) if x_label is not None: ax.set_xlabel(x_label) return ax
def plot_project_total_over_timespan(axes: plt.Axes, projects_dict: dict, start_datetime=datetime.datetime.now(), end_datetime=datetime.datetime.now() ) -> plt.Axes: # Convenience feature: The start and end datetime can be given as strings, as that # is often a lot easier for the user. These will be automatically converted into # datetime objects datetime_format = '%Y-%m-%d' if isinstance(start_datetime, str): start_datetime = datetime.datetime.strptime(start_datetime, datetime_format) if isinstance(end_datetime, str): end_datetime = datetime.datetime.strptime(end_datetime, datetime_format) # ~ Population plot projects_total = defaultdict(float) for index, (project_id, project_data) in enumerate(projects_dict.items(), start=1): for date_string, hours in project_data['daily_hours'].items(): dt = datetime.datetime.strptime(date_string, datetime_format) if start_datetime <= dt <= end_datetime: projects_total[project_id] += hours # Now after the previous loop over all entries of daily working hours # have been processed we can plot the final value for the current project total_hours = projects_total[project_id] axes.barh(y=index, width=total_hours, label=project_data['label'], color=project_data['color']) # Besides the bar itself there will also be a text label with the actual value axes.text(y=index, x=total_hours + 0.05, s=f'{total_hours:0.2f}', fontsize='large', va='center') # ~ Additional plot info total_hours = sum(hours for hours in projects_total.values()) max_hours = max(hours for hours in projects_total.values()) axes.set_title(f'Total hours: {total_hours:0.2f}') axes.set_yticks(list(range(1, len(projects_total) + 1))) axes.set_yticklabels([d['label'] for d in projects_dict.values()]) axes.set_xlabel('time in hours') axes.set_xlim(0, max_hours + 2) axes.legend() return axes
def plot_params(self, named_bounded_params: Sequence[Tuple[ str, BoundedParameter]] = None, exclude: Iterable[str] = (), cmap='coolwarm', ax: plt.Axes = None) -> mpl.container.BarContainer: if ax is None: ax = plt.gca() ax = plt.gca() names, v, grad, lb, ub, requires_grad = self.get_named_bounded_params( named_bounded_params, exclude=exclude) max_grad = np.amax(np.abs(grad)) if max_grad == 0: max_grad = 1. v01 = (v - lb) / (ub - lb) grad01 = (grad + max_grad) / (max_grad * 2) n = len(v) grad01[~requires_grad] = np.nan # (np.amin(grad01) + np.amax(grad01)) / 2 # ax = plt.gca() # CHECKED for i, (lb1, v1, ub1, g1, r1) in enumerate(zip(lb, v, ub, grad, requires_grad)): color = 'k' if r1 else 'gray' plt.text(0, i, '%1.2g' % lb1, ha='left', va='center', color=color) plt.text(1, i, '%1.2g' % ub1, ha='right', va='center', color=color) plt.text( 0.5, i, '%1.2g %s' % (v1, ('(e%1.0f)' % np.log10(np.abs(g1))) if r1 else '(fixed)'), ha='center', va='center', color=color) lut = 256 colors = plt.get_cmap(cmap, lut)(grad01) for i, r in enumerate(requires_grad): if not r: colors[i, :3] = np.array([0.95, 0.95, 0.95]) h = ax.barh(np.arange(n), v01, left=0, color=colors) ax.set_xlim(-0.025, 1) ax.set_xticks([]) ax.set_yticks(np.arange(n)) names = [v.replace('_', '-') for v in names] ax.set_yticklabels(names) ax.set_ylim(n - 0.5, -0.5) plt2.box_off(['top', 'right', 'bottom']) plt2.detach_axis('x', amin=0, amax=1) plt2.detach_axis('y', amin=0, amax=n - 1) # plt.show() # CHECKED return h
def plot_prediction_bar(ax: plt.Axes, predictions: torch.Tensor, class_names: List, k: int = 10): """Draws top k best predictions on given plt.Axes. Args: ax (plt.Axes): Axes on which to draw. predictions (torch.Tensor): Predictions from neural network, has to be projected to probabilities(ie. softmax) for proper plotting. class_names (List): Names of classes. k (int, optional): How much bars to plot. Defaults to 10. """ argsorted = torch.argsort(predictions, descending=True) entropy = torch.sum(-predictions * torch.log2(predictions)) top_predictions = predictions[argsorted[:k]] top_predictions_names = [class_names[arg] for arg in argsorted[:k]] ax.barh(top_predictions_names, top_predictions, height=0.8) ax.set_xlim(0.0, 1.0) ax.set_xlabel("Probability") ax.set_title(f"Entropy: {entropy:.5f}")
def plot_positive_negative_bars(ax: plt.Axes, values: pd.Series, positive_dict: dict = None, negative_dict: dict = None, title='Significant Spearman Correlation', x_label='Spearman Correlation'): if positive_dict is None: positive_dict = {} if negative_dict is None: negative_dict = {} default_positive_dict = {'color': 'green', 'height': 0.2} default_negative_dict = {'color': 'red', 'height': 0.2} positive_dict = set_default_parameters(positive_dict, default_positive_dict) negative_dict = set_default_parameters(negative_dict, default_negative_dict) sorted_values = values.sort_values() y_position = np.arange(len(sorted_values)) positive_values = sorted_values.apply(lambda x: x if x >= 0 else 0) ax.barh(y_position, positive_values, **positive_dict) negative_values = sorted_values.apply(lambda x: x if x < 0 else 0) ax.barh(y_position, negative_values, **negative_dict) ax.set_yticks(y_position) ax.set_yticklabels(sorted_values.index) fat_bar_number = 5 if len(y_position) < fat_bar_number: ax.set_ylim([ i + np.sign(i) * (fat_bar_number - len(y_position)) for i in ax.get_ylim() ]) # ax.set_xlim((1,10)) ax.set_title(title) ax.set_xlabel(x_label) return ax
def plot_frequencies(ax: plt.Axes, freq_series, top_count=30): top_n = freq_series.iloc[:top_count] ax.barh(top_n.index, top_n) ax.invert_yaxis()
def draw_impact_barh( ax: plt.Axes, df: pd.DataFrame, hi_color: str = "steelblue", lo_color: str = "mediumturquoise", height_fill: float = 0.8, height_line: float = 0.8, ) -> tuple[plt.Axes, plt.Axes]: """Draw the impact plot. Parameters ---------- ax : matplotlib.axes.Axes Axes for the "delta mu" impact. df : pandas.DataFrame Dataframe containing impact information. hi_color : str Up variation color. lo_color : str Down variation color. height_fill : float Height for the filled bars (post-fit). height_line : float Height for the line (unfilled) bars (pre-fit). Returns ------- matplotlib.axes.Axes Axes for the impact: "delta mu". matplotlib.axes.Axes Axes for the nuisance parameter pull. """ ys = np.array(df.ys) ax.barh( ys, df.pre_down.abs(), height=height_line, left=df.pre_down_lefts, fill=False, edgecolor=lo_color, zorder=5, label=r"Prefit $\theta=\hat{\theta}-\Delta\theta$", ) ax.barh( ys, df.pre_up.abs(), height=height_line, left=df.pre_up_lefts, fill=False, edgecolor=hi_color, zorder=5, label=r"Prefit $\theta=\hat{\theta}+\Delta\theta$", ) ax.barh( ys, df.post_down.abs(), height=height_fill, left=df.post_down_lefts, fill=True, color=lo_color, zorder=6, label=r"Postfit $\theta=\hat{\theta}-\Delta\theta$", ) ax.barh( ys, df.post_up.abs(), height=height_fill, left=df.post_up_lefts, fill=True, color=hi_color, zorder=6, label=r"Postfit $\theta=\hat{\theta}+\Delta\theta$", ) xlims = float(np.amax([np.abs(df.pre_down), np.abs(df.pre_up)]) * 1.25) if xlims > 0.25: xlims = 0.24 ax.set_xlim([-xlims, xlims]) ax.set_yticks(ys) ax2 = ax.twiny() ax2.errorbar( df.central, ys, xerr=[np.abs(df.sig_lo), df.sig_hi], fmt="ko", zorder=999, label="Nuisance Parameter Pull", ) ax2.set_xlim([-1.8, 1.8]) ax2.plot([-1, -1], [-0.5, ys[-1] + 0.5], ls="--", color="black") ax2.plot([1, 1], [-0.5, ys[-1] + 0.5], ls="--", color="black") ax2.xaxis.set_ticks_position("bottom") ax.yaxis.set_ticks_position("none") ax.xaxis.set_ticks_position("top") return ax, ax2