def plot(self, ax: Axes, obj: Object, zorder: int = 1) -> Axes: bar1_values = obj.bar1_values bar2_values = obj.bar2_values label1 = obj.label1 label2 = obj.label2 xticklabels = obj.xticklabels width = obj.bar_width x = np.arange(len(xticklabels)) # the label locations ax.set_xticks(x) ax.set_xticklabels(xticklabels) ax.bar(x - width / 2, bar1_values, label=label1, zorder=zorder, width=width) ax.bar(x + width / 2, bar2_values, label=label2, zorder=zorder, width=width) ax.legend(prop={'size': obj.legendsize}) return ax
def insert_multicategory_histogram(plt_axis: Axes, stat_dicts: List[Dict[str, Any]], key_order: List[str] = None, bar_titles: List[str] = None, title: str = None) -> Axes: """ Given a final log dictionaries creates a histogram on the given Axes object. :param plt_axis: A matplotlib.axes.Axes object representing the matplotlib axes you wish to draw on. :param stat_dicts: A List[Dict[str, Any]] containing all the final log dictionaries you wish to draw a histogram for. :param key_order: (Optional) A List[str] containing the keys of the final log dictionary you wish to draw form. Defaults to None (draws nothing). :param bar_titles: (Optional) A List[str] containing the histogram x-axis labels. Defaults to None (takes key_order as reference). :param title: (Optional) A str representing the title of the subplot. Defaults to None (no title). :return: A matplotlib.axes.Axes object (same as the one passed). Useful for chaining calls. """ if key_order is None: key_order = list(stat_dicts[0].keys()) if bar_titles is None: bar_titles = list(key_order) width = (1 - 0.2) / len(stat_dicts) offsets = [ -(width * (len(stat_dicts) // 2)) + (x * width) for x in range(len(stat_dicts)) ] for i, key in enumerate(key_order): plt_axis.bar(x=[i + x for x in offsets], height=[stat_dict[key] for stat_dict in stat_dicts], width=width - 0.01, align="center") plt_axis.set_xticks(range(len(bar_titles))) plt_axis.set_xticklabels(bar_titles, fontsize=16) if title is not None: plt_axis.set_title(title, fontsize=16) plt_axis.autoscale(tight=True) return plt_axis
def plot(self, ax: Axes) -> None: if self.display == 'plot': ax.plot(self.X, self.Y) elif self.display == 'bar': ax.bar(self.X, self.Y) ax.set_xticklabels(self.X, rotation='vertical') ax.set_xlabel(self.xlabel) ax.set_ylabel(self.ylabel) ax.set_title(self.title)
def plot_volume(ax: Axes, kline: pandas.DataFrame, color: str = 'b', alpha: float = 1) -> Axes: figure: Figure = ax.figure f_width = figure.get_figwidth() bar_take_axes_size_percentage = 0.9 bar_width = f_width * bar_take_axes_size_percentage / len( kline) / ax.numCols ax.bar(date2num(kline.index.to_pydatetime()), kline['volume'].values, color=color, alpha=alpha, width=bar_width) return _adjust_axe_timeaxis_view(ax)
def draw_re_pdec_on_ax(df, ax: Axes): diverse_tasks = [ "ReEncrypt", "PartialDecryption", #"PartialReEncryptionKey", #"ReEncryptionKeyCombination", ] t_data = df.loc[df.task.isin(diverse_tasks)] x_data = t_data.task x_data = pandas.Series(["PD", "RE"]) plot = ax.bar(x=x_data, height=t_data.time, width=0.2) # , color='#214355') ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['bottom'].set_color('#DDDDDD') autolabel(plot, ax) # include grid lines behind bars ax.set_axisbelow(True) ax.grid(axis='y', color="#DDDDDD") # ticks and labels ax.tick_params(axis='x', rotation=90) ax.tick_params(axis='both', color="#DDDDDD") ax.yaxis.set_tick_params(labelleft=False)
def bar(self, left, height, zs=0, zdir='z', *args, **kwargs): ''' Add 2D bar(s). ========== ================================================ Argument Description ========== ================================================ *left* The x coordinates of the left sides of the bars. *height* The height of the bars. *zs* Z coordinate of bars, if one value is specified they will all be placed at the same z. *zdir* Which direction to use as z ('x', 'y' or 'z') when plotting a 2d set. ========== ================================================ Keyword arguments are passed onto :func:`~matplotlib.axes.Axes.bar`. Returns a :class:`~mpl_toolkits.mplot3d.art3d.Patch3DCollection` ''' had_data = self.has_data() patches = Axes.bar(self, left, height, *args, **kwargs) if not cbook.iterable(zs): zs = np.ones(len(left))*zs verts = [] verts_zs = [] for p, z in zip(patches, zs): vs = p.get_verts() verts += vs.tolist() verts_zs += [z] * len(vs) art3d.patch_2d_to_3d(p, zs, zdir) if 'alpha' in kwargs: p.set_alpha(kwargs['alpha']) xs, ys = zip(*verts) xs, ys, verts_zs = art3d.juggle_axes(xs, ys, verts_zs, zdir) self.auto_scale_xyz(xs, ys, verts_zs, had_data) return patches
def plot_bar( axes: Axes, x: float, y: float, std: float, min_std: float, bar_width: float, vertical: bool, **kwargs ): """Plot bar with given properties. Parameters ---------- axes: Axes, Axes object where to plot the bar. x: float, Position for the left size of the bar. y: float, Height of the considered bar. std: float, Standard deviation to plot on top. min_std: float, Minimum standard deviation to be shown. bar_width: float, Width of the bar. vertical: bool, Whetever to build the axis to show the bars as vertical or as horizontal. """ if vertical: axes.bar( x=x, height=y, width=bar_width, **({"yerr": std} if std > min_std else {}), capsize=5, **kwargs ) else: axes.barh( y=x, width=y, height=bar_width, **({"xerr": std} if std > min_std else {}), capsize=5, **kwargs )
def plot(self, ax: Axes, obj: Object, zorder: int = 1) -> Axes: assert obj.bars_value is not None assert obj.labels is not None bars_value = obj.bars_value labels = obj.labels ax.bar(list(range(len(bars_value))), bars_value, tick_label=labels, zorder=zorder) # # for tick in ax.xaxis.get_major_ticks(): # # specify integer or one of preset strings, e.g. # tick.label.set_fontsize(obj.xla) # # tick.label.set_rotation('vertical') return ax
def bar(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs): """Bar plot of 1D histograms.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) value_format = kwargs.pop("value_format", None) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) label = kwargs.pop("label", h1.name) lw = kwargs.pop("linewidth", kwargs.pop("lw", 0.5)) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) data = get_data(h1, cumulative=cumulative, density=density) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) else: colors = kwargs.pop("color", kwargs.pop("c", None)) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) kwargs["yerr"] = err_data if "ecolor" not in kwargs: kwargs["ecolor"] = "black" _add_labels(ax, h1, kwargs) ax.bar(h1.bin_left_edges, data, h1.bin_widths, align="edge", label=label, color=colors, linewidth=lw, **kwargs) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats)
def plot_mass_spec(ax: Axes, mass_spec: MassSpectrum, **kwargs) -> BarContainer: """ Plots a Mass Spectrum :param ax: The axes to plot the MassSpectrum on :type ax: matplotlib.axes.Axes :param mass_spec: The mass spectrum to plot :type mass_spec: :class`pyms.Spectrum.MassSpectrum` :Other Parameters: :class:`matplotlib.lines.Line2D` properties. Used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. Example:: >>> plot_mass_spec(im.get_ms_at_index(5), linewidth=2) >>> ax.set_title(f"Mass spec for peak at time {im.get_time_at_index(5):5.2f}") See https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.lines.Line2D.html for the list of possible kwargs :return: Container with all the bars and optionally errorbars. :rtype: :class:`matplotlib.container.BarContainer` """ if not isinstance(mass_spec, MassSpectrum): raise TypeError("'mass_spec' must be a MassSpectrum") mass_list = mass_spec.mass_list intensity_list = mass_spec.mass_spec if "width" not in kwargs: kwargs["width"] = 0.5 # to set x axis range find minimum and maximum m/z channels min_mz = mass_list[0] max_mz = mass_list[-1] for idx, mass in enumerate(mass_list): if mass_list[idx] > max_mz: max_mz = mass_list[idx] for idx, mass in enumerate(mass_list): if mass_list[idx] < min_mz: min_mz = mass_list[idx] plot = ax.bar(mass_list, intensity_list, **kwargs) # Set axis ranges ax.set_xlim(min_mz - 1, max_mz + 1) ax.set_ylim(bottom=0) return plot
def plot_single_df(ax: Axes, x: List[int], data: pd.DataFrame, label: str = "Read1", show_y: bool = True): ax.bar(x, data["Count"], alpha=0.7, color=mcolors.TABLEAU_COLORS['tab:purple'], align='center', label=f"{label} Read Count") for i, l in zip(['A', 'G', 'C', 'T'], ['tab:green', 'tab:orange', 'tab:blue', 'tab:red']): ax.plot(x, data[i], color=mcolors.TABLEAU_COLORS[l], label=f"{label} {i}") ax.scatter(x, [x * 100 for x in data['N']], s=3, color=mcolors.TABLEAU_COLORS['tab:gray'], alpha=0.7, linewidths=0.5, label=f"{label} N(‱)") ax.plot(x, data['Q20'], color=mcolors.TABLEAU_COLORS['tab:olive'], label=f"{label} Q20") ax.plot(x, data['Q30'], color=mcolors.TABLEAU_COLORS['tab:cyan'], label=f"{label} Q30") ax.set_xlabel(f"{label} Cycles") if show_y: ax.set_ylabel("Percentage") else: ax.axes.yaxis.set_visible(False) ax.set_yticks([x / 100. for x in range(0, 101, 20)]) ax.set_yticklabels([f'{x}%' for x in range(0, 101, 20)])
def make_bars(axes: Axes, x_location, heights, width, labels, bar_error=None): bars = {} i = 0 for soil_label, height in zip(labels, heights): if bar_error is not None: bar = axes.bar(x=x_location + i, height=height, width=width, yerr=bar_error[soil_label], label=soil_label, color=COLORS[soil_label]) else: bar = axes.bar(x=x_location + i, height=height, width=width, label=soil_label, color=COLORS[soil_label]) i += width bars[soil_label] = bar return bars
def polar_map(hist: Histogram2D, ax: Axes, *, show_zero: bool = True, show_colorbar: bool = True, **kwargs): """Polar map of polar histograms. Similar to map, but supports less parameters.""" data = get_data(hist, cumulative=False, flatten=True, density=kwargs.pop("density", False)) cmap = _get_cmap(kwargs) norm, cmap_data = _get_cmap_data(data, kwargs) colors = cmap(cmap_data) rpos, phipos = (arr.flatten() for arr in hist.get_bin_left_edges()) dr, dphi = (arr.flatten() for arr in hist.get_bin_widths()) rmax, _ = (arr.flatten() for arr in hist.get_bin_right_edges()) bar_args = {} if "zorder" in kwargs: bar_args["zorder"] = kwargs.pop("zorder") alphas = _get_alpha_data(cmap_data, kwargs) if np.isscalar(alphas): alphas = np.ones_like(data) * alphas for i in range(len(rpos)): if data[i] > 0 or show_zero: bin_color = colors[i] # TODO: align = "edge" bars = ax.bar(phipos[i], dr[i], width=dphi[i], bottom=rpos[i], align='edge', color=bin_color, edgecolor=kwargs.get("grid_color", cmap(0.5)), lw=kwargs.get("lw", 0.5), alpha=alphas[i], **bar_args) ax.set_rmax(rmax.max()) if show_colorbar: _add_colorbar(ax, cmap, cmap_data, norm)
def time_of_appearance_frequency(ax: Axes, plate: Plate, plot_color: str, timestamps: List[timedelta] = None, bar: bool = False) -> List: """ Add a time of appearance frequency bar or line plot to an axis :param ax: a Matplotlib Axes object to add a plot to :param plate: a Plate instance :param plot_color: a Colormap color :param timestamps: a list of timedeltas used to rescale the plot :param bar: if a bar plot should be used instead of the default line plot :returns: either a list of matplotlib.lines.Line2D or matplotlib.patches.Rectangle objects """ from collections import Counter timestamps = dict.fromkeys( [timestamp.total_seconds() / 3600 for timestamp in timestamps], 0) appearance_counts = Counter(colony.time_of_appearance for colony in plate.items) # Normalise counts to frequency appearance_counts = { timestamp.total_seconds() / 3600: count / sum(appearance_counts.values()) for timestamp, count in appearance_counts.items() } # Merge counts into default values dictionary appearance_counts = {**timestamps, **appearance_counts} ax.set_xlabel("Elapsed time (hours)") ax.set_ylabel("Frequency") if bar: return ax.bar(*zip(*sorted(appearance_counts.items())), color=plot_color, label=f"Plate {plate.id}", alpha=0.8) else: return ax.plot(*zip(*sorted(appearance_counts.items())), color=plot_color, label=f"Plate {plate.id}", alpha=0.8)
def plot_stacked_bars(axes: Axes, x_location, heights, errors, labels, parameter_names): bars = {} for height, error, label, name in zip(heights, errors, labels, parameter_names): error_kw = {'elinewidth': 0.8} bar = axes.bar(x=x_location, height=height, width=BAR_WIDTH, yerr=error, label=label, color=COLORS[name], capsize=2, error_kw=error_kw) bars[name] = bar return bars
def bar(self, left, height, zs=0, zdir='z', *args, **kwargs): ''' Add 2D bar(s). ========== ================================================ Argument Description ========== ================================================ *left* The x coordinates of the left sides of the bars. *height* The height of the bars. *zs* Z coordinate of bars, if one value is specified they will all be placed at the same z. *zdir* Which direction to use as z ('x', 'y' or 'z') when plotting a 2d set. ========== ================================================ Keyword arguments are passed onto :func:`~matplotlib.axes.Axes.bar`. Returns a :class:`~mpl_toolkits.mplot3d.art3d.Patch3DCollection` ''' had_data = self.has_data() patches = Axes.bar(self, left, height, *args, **kwargs) if not cbook.iterable(zs): zs = np.ones(len(left)) * zs verts = [] verts_zs = [] for p, z in zip(patches, zs): vs = art3d.get_patch_verts(p) verts += vs.tolist() verts_zs += [z] * len(vs) art3d.patch_2d_to_3d(p, zs, zdir) if 'alpha' in kwargs: p.set_alpha(kwargs['alpha']) xs, ys = zip(*verts) xs, ys, verts_zs = art3d.juggle_axes(xs, ys, verts_zs, zdir) self.auto_scale_xyz(xs, ys, verts_zs, had_data) return patches
def Graphing_BarChart(labels: list, values: list, ax: axes.Axes, label="Default Bar Chart Label", colours=[CMAP(j) for j in range(1, 10)], Labels=True): """Bar chart constructor for given labels and sizes. **Args:** labels(list): The labels to be applied to the chart values(list): The values to be charted ax(axes.Axes): The axis object to bind to label(str): The optional header title for the bar chart """ width = 1 fontSize = 12 scaleFactor_float = 1.6 n_labels = len(labels) x = np.arange(n_labels) scaled_x = [ scaleFactor_float * i for i in x ] # calculate length of x-axis then scale to match pie charts above rects = ax.bar(scaled_x, values, width, color=colours, label=label) if Labels: try: ax.set_xticklabels( [label.capitalize().replace('_', ' ') for label in labels]) except AttributeError: # if a numpy.datetime64 object is passed, this is thrown. ax.set_xticklabels(labels) ax.set_xticks(scaled_x) plt.setp(ax.xaxis.get_majorticklabels(), rotation=45) return
def plot_z_trends(self, axis: Axes = None) -> None: if axis is None: axis = self.figure.add_subplot(111) cluster = Cluster(simulation_name=self.simulation.simulation_name, clusterID=0, redshift='z000p000') aperture_float = self.get_apertures(cluster)[ self.aperture_id] / cluster.r200 if not os.path.isfile( os.path.join( self.path, f'redshift_rot0rot4_bootstrap_aperture_{self.aperture_id}.npy' )): warnings.warn( f"File redshift_rot0rot4_bootstrap_aperture_{self.aperture_id}.npy not found." ) print("self.make_simbootstrap() activated.") self.make_simbootstrap() print( f"Retrieving npy files: redshift_rot0rot4_bootstrap_aperture_{self.aperture_id}.npy" ) sim_bootstrap = np.load(os.path.join( self.path, f'redshift_rot0rot4_bootstrap_aperture_' f'{self.aperture_id}.npy'), allow_pickle=True) sim_bootstrap = np.asarray(sim_bootstrap) items_labels = f""" REDSHIFT TRENDS Number of clusters: {self.simulation.totalClusters:d} $z$ = 0.0 - 1.8 Aperture radius = {aperture_float:.2f} $R_{{200\ true}}$""" print(items_labels) sim_colors = { 'ceagle': 'pink', 'celr_e': 'lime', 'celr_b': 'orange', 'macsis': 'aqua', } axis.axhline(90, linestyle='--', color='k', alpha=0.5, linewidth=2) axis.plot(sim_bootstrap[0, 0], sim_bootstrap[3, 0], color=sim_colors[self.simulation.simulation_name], alpha=1, linestyle='none', marker='^', markersize=10) axis.plot(sim_bootstrap[0, 0], sim_bootstrap[2, 0], color=sim_colors[self.simulation.simulation_name], alpha=1, linestyle='none', marker='o', markersize=10) axis.plot(sim_bootstrap[0, 0], sim_bootstrap[1, 0], color=sim_colors[self.simulation.simulation_name], alpha=1, linestyle='none', marker='v', markersize=10) for marker_index in range(len(sim_bootstrap[0, 0])): if marker_index is 0: align_toggle = 'edge' x_edge_left = sim_bootstrap[0, 0][marker_index] x_edge_right = sim_bootstrap[ 0, 0][marker_index] + sim_bootstrap[0, 1][marker_index] else: align_toggle = 'center' x_edge_left = sim_bootstrap[ 0, 0][marker_index] - sim_bootstrap[0, 1][marker_index] / 2 x_edge_right = sim_bootstrap[ 0, 0][marker_index] + sim_bootstrap[0, 1][marker_index] / 2 axis.plot([x_edge_left, x_edge_right], [ sim_bootstrap[3, 0][marker_index], sim_bootstrap[3, 0][marker_index] ], color=sim_colors[self.simulation.simulation_name], alpha=0.8, linestyle='--', lw=1.5) axis.plot([x_edge_left, x_edge_right], [ sim_bootstrap[2, 0][marker_index], sim_bootstrap[2, 0][marker_index] ], color=sim_colors[self.simulation.simulation_name], alpha=0.8, linestyle='-', lw=1.5) axis.plot([x_edge_left, x_edge_right], [ sim_bootstrap[1, 0][marker_index], sim_bootstrap[1, 0][marker_index] ], color=sim_colors[self.simulation.simulation_name], alpha=0.8, linestyle='-.', lw=1.5) axis.bar(sim_bootstrap[0, 0][marker_index], 2 * sim_bootstrap[3, 1][marker_index], bottom=sim_bootstrap[3, 0][marker_index] - sim_bootstrap[3, 1][marker_index], width=sim_bootstrap[0, 1][marker_index], align=align_toggle, color=sim_colors[self.simulation.simulation_name], alpha=0.2, edgecolor='none', linewidth=0) axis.bar(sim_bootstrap[0, 0][marker_index], 2 * sim_bootstrap[2, 1][marker_index], bottom=sim_bootstrap[2, 0][marker_index] - sim_bootstrap[2, 1][marker_index], width=sim_bootstrap[0, 1][marker_index], align=align_toggle, color=sim_colors[self.simulation.simulation_name], alpha=0.2, edgecolor='none', linewidth=0) axis.bar(sim_bootstrap[0, 0][marker_index], 2 * sim_bootstrap[1, 1][marker_index], bottom=sim_bootstrap[1, 0][marker_index] - sim_bootstrap[1, 1][marker_index], width=sim_bootstrap[0, 1][marker_index], align=align_toggle, color=sim_colors[self.simulation.simulation_name], alpha=0.2, edgecolor='none', linewidth=0) perc84 = Line2D([], [], color='k', marker='^', linestyle='--', markersize=10, label=r'$84^{th}$ percentile') perc50 = Line2D([], [], color='k', marker='o', linestyle='-', markersize=10, label=r'median') perc16 = Line2D([], [], color='k', marker='v', linestyle='-.', markersize=10, label=r'$16^{th}$ percentile') patch_ceagle = Patch(facecolor=sim_colors['ceagle'], label='C-EAGLE', edgecolor='k', linewidth=1) patch_celre = Patch(facecolor=sim_colors['celr_e'], label='CELR-E', edgecolor='k', linewidth=1) patch_celrb = Patch(facecolor=sim_colors['celr_b'], label='CELR-B', edgecolor='k', linewidth=1) patch_macsis = Patch(facecolor=sim_colors['macsis'], label='MACSIS', edgecolor='k', linewidth=1) leg1 = axis.legend(handles=[perc84, perc50, perc16], loc='lower right', handlelength=3, fontsize=20) leg2 = axis.legend( handles=[patch_ceagle, patch_celre, patch_celrb, patch_macsis], loc='lower left', handlelength=1, fontsize=20) axis.add_artist(leg1) axis.add_artist(leg2) axis.text(0.03, 0.97, items_labels, horizontalalignment='left', verticalalignment='top', transform=axis.transAxes, size=15) axis.set_xlabel(r"$z$", size=25) axis.set_ylabel( r"$\Delta \theta \equiv (\mathbf{L},\mathrm{\widehat{CoP}},\mathbf{v_{pec}})$\quad[degrees]", size=25) axis.set_ylim(0, 180)
def add_histogram(ax: Axes, data: np.ndarray, xlabel: Optional[str] = None, ylabel: str = 'Counts', title: str = None, bins: int = 10, draw_bars: bool = True, bar_width: float = 0.7, range: Optional[Tuple[float]] = None, fit_dist: Optional[str] = None, fit_dist_color: str = 'r', kernel_smoothing: bool = True, kernel_label: Optional[str] = None, label_kernel_peaks: Optional[str] = None, kernel_smoothing_color: str = 'c', kernel_bandwidth: Optional[str] = None, vlines: Optional[List[float]] = None, vline_colors: Optional[List[str]] = 'b', normalize: bool = False): """ Add a histogram plot Basic Usage: .. code-block:: python fig, ax = plt.subplots(1, 1) histogram(ax, np.random.rand(64, 64), draw_bars=True, kernel_smoothing=True, fit_dist='poisson', vlines=[0.25, 0.75]) This will draw the histogram with a kernel smoothed fit, a poisson fit, and vertical lines at x coordinates 0.25 and 0.75. :param Axes ax: The axis to add the histogram to :param ndarray data: The data to make the histogram for :param str xlabel: Label for the x axis :param str ylabel: Label for the y axis :param str title: Title for the axis :param int bins: Number of bins in the histogram :param bool draw_bars: If True, draw the histogram bars :param float bar_width: The width of the bars to plot :param tuple[float] range: The range to fit bins to (argument to np.histogram) :param str fit_dist: The name of a distribution to fit to the data :param str fit_dist_color: The color of the fit dist line :param bool kernel_smoothing: If True, plot the kernel smoothed line over the bars :param str kernel_label: If not None, label for the kernel smoothed line :param str label_kernel_peaks: Any of min, max, both to label extrema in the kernel :param str kernel_smoothing_color: The color of the kernel smoothed fit line :param str kernel_bandwidth: The method to calculate the kernel width with :param list[float] vlines: x coords to draw vertical lines at :param list[str] vline_colors: The color or list of colors for the spectra :param bool normalize: If True, normalize the counts/KDE/models """ # Estimate the histogram data = data[np.isfinite(data)] xbins, hist, kernel_x, kernel_y = get_histogram( data, bins=bins, range=range, kernel_smoothing=kernel_smoothing, kernel_bandwidth=kernel_bandwidth, normalize=normalize) width = bar_width * (xbins[1] - xbins[0]) center = (xbins[:-1] + xbins[1:]) / 2 # Add bars for the histogram if draw_bars: ax.bar(center, hist, align='center', width=width) # Estimate the kernel smoothed fit if kernel_smoothing: # Add a kernel smoothed fit ax.plot(kernel_x, kernel_y, color=kernel_smoothing_color, label=kernel_label) if label_kernel_peaks in ('max', 'both', True): maxima = (np.diff(np.sign(np.diff(kernel_y))) < 0).nonzero()[0] + 1 kx_maxima = kernel_x[maxima] ky_maxima = kernel_y[maxima] ax.plot(kx_maxima, ky_maxima, 'oc') for kx, ky in zip(kx_maxima, ky_maxima): ax.text(kx, ky * 1.05, "{}".format(float(f"{kx:.2g}")), color="c", fontsize=12) if label_kernel_peaks in ('min', 'both', True): minima = (np.diff(np.sign(np.diff(kernel_y))) > 0).nonzero()[0] + 1 kx_minima = kernel_x[minima] ky_minima = kernel_y[minima] ax.plot(kx_minima, ky_minima, 'oy') for kx, ky in zip(kx_minima, ky_minima): ax.text(kx, ky * 0.88, "{}".format(float(f"{kx:.2g}")), color="y", fontsize=12) # Fit an model distribution to the data if fit_dist is not None: opt_x = np.linspace(xbins[0], xbins[-1], 100) if fit_dist == 'gamma': fit_alpha, fit_loc, fit_beta = gamma.fit(data + 1e-5) # print(fit_alpha, fit_loc, fit_beta) opt_y = data = gamma.pdf( opt_x, fit_alpha, loc=fit_loc, scale=fit_beta) * data.shape[0] else: raise KeyError(f'Unknown fit distribution: {fit_dist}') ax.plot(opt_x, opt_y, fit_dist_color) # Add spectral lines if vlines is None: vlines = [] if isinstance(vlines, (int, float)): vlines = [vlines] if isinstance(vline_colors, (str, tuple)): vline_colors = [vline_colors for _ in vlines] if len(vlines) != len(vline_colors): raise ValueError( f'Number of colors and lines needs to match: {vlines} vs {vline_colors}' ) ymin, ymax = ax.get_ylim() for vline, vline_color in zip(vlines, vline_colors): ax.vlines(vline, ymin, ymax, colors=vline_color) # Label the axes if xlabel not in (None, ''): ax.set_xlabel(xlabel) if ylabel not in (None, ''): ax.set_ylabel(ylabel) if title not in (None, ''): ax.set_title(f'{title} (n={data.shape[0]})') else: ax.set_title(f'n = {data.shape[0]}')
def plot(self, ax: axes.Axes) -> None: if self._studies is None: return if ( self._frequency != DAILY and self._frequency != WEEKLY and self._frequency != INTRADAY_60MINUTES ): return mn, mx = ax.get_ylim() regex = re.compile(r"^(\d{8})(?:[T\s](\d{2}:\d{2}))*$") for study in self._studies: match = regex.match(study["start"]) start = datetime.strptime(match.group(1), "%Y%m%d") match = regex.match(study["end"]) end = datetime.strptime(match.group(1), "%Y%m%d") if self._frequency == WEEKLY: start = start - timedelta(days=start.weekday()) end = end - timedelta(days=end.weekday()) if self._frequency == INTRADAY_60MINUTES: match = regex.match(study["start"]) if match.group(2) is not None: start = datetime.strptime( f"{match.group(1)}T{match.group(2)}", "%Y%m%dT%H:%M" ) else: continue match = regex.match(study["end"]) if match.group(2) is not None: end = datetime.strptime( f"{match.group(1)}T{match.group(2)}", "%Y%m%dT%H:%M" ) else: continue assert start is not None assert end is not None try: start_index = self._quotes.index.get_loc( start, ) end_index = self._quotes.index.get_loc( end, ) except KeyError: continue color = "" if study["operation"] == "long": color = self._color_entry elif study["operation"] == "short": color = self._color_entry elif study["operation"] == "close": color = self._color_close elif study["operation"] == "warning": color = self._color_warning else: raise ValueError(f"invalid study operation: {study['operation']}") ax.bar( start_index - (self._candlesticks_body_width / 2.0), width=(end_index - start_index) + self._candlesticks_body_width, bottom=mn, height=mx - mn, align="edge", color=color, alpha=self._alpha, )
def _time_range(self, ax: axes.Axes, range_type: str) -> None: anchor_x = 0 assert range_type in ("d", "m", "y") if range_type == "m": current = self._quotes.index[0].to_pydatetime().month elif range_type == "y": current = self._quotes.index[0].to_pydatetime().year # elif range_type == "d": # current = self._quotes.index[0].to_pydatetime().day # current = 16 plotting = self._from_start mn, mx = ax.get_ylim() for i, x in enumerate(self._quotes.index): if range_type == "m": cursor = x.to_pydatetime().month elif range_type == "y": cursor = x.to_pydatetime().year elif range_type == "d": cursor = x.to_pydatetime().hour if x.to_pydatetime().minute != 0: continue if range_type in ("m", "y"): if cursor != current: plotting = not plotting current = cursor if plotting is False: ax.bar( anchor_x, width=i - anchor_x, bottom=mn, height=mx - mn, align="edge", color=self._color, alpha=self._alpha, ) else: anchor_x = i else: market_open = 17 if self._market == "US": market_open = 17 elif self._market == "EU": market_open = 19 if cursor == market_open: plotting = not plotting if plotting is False: ax.bar( anchor_x, width=i - 1 - anchor_x, # width=i - anchor_x, bottom=mn, height=mx - mn, align="edge", color=self._color, alpha=self._alpha, ) else: anchor_x = i if plotting is True: ax.bar( anchor_x, width=(len(self._quotes) - 1) - anchor_x, bottom=mn, height=mx - mn, align="edge", color=self._color, alpha=self._alpha, )
def show_one_main( stat_sub_array: list, stat_all_array: list, stat_name_array: list, *, ax: Axes = None, title: str = None, ylabel: str = None, yticks=(0, 0.2, 0.4, 0.6, 0.8, 1), yticklabels=('0', '0.2', '0.4', '0.6', '0.8', '1'), color_list=None, stat_ref_name='cnn', ): # based on https://github.com/leelabcnbc/tang_jcompneuro/blob/master/thesis_plots/v1_fitting/results_basic.ipynb assert len(stat_sub_array) == len(stat_all_array) == len(stat_name_array) if ax is None: ax = plt.gca() if color_list is None: # https://matplotlib.org/examples/color/colormaps_reference.html color_list = plt.get_cmap('Set1').colors stat_all_ref = stat_all_array[stat_name_array.index(stat_ref_name)] counter_now = 0 label_grp = [] rect_grp = [] for model_class_idx, (stat_sub, stat_all, stat_name) in enumerate( zip(stat_sub_array, stat_all_array, stat_name_array)): num_model_this = len(stat_sub) model_names, model_perfs = zip(*stat_sub) rects_this = ax.bar(counter_now + np.arange(num_model_this) + 1, model_perfs, 0.95, color=color_list[model_class_idx]) label_grp.append(stat_name) rect_grp.append(rects_this[0]) for text_idx, text in enumerate(model_names): ax.text(text_idx + 1 + counter_now, model_perfs[text_idx], s=text, rotation='vertical', horizontalalignment='center', verticalalignment='top', color='white', fontsize='small') assert stat_all is not None rc, = ax.plot([counter_now + 0.5, counter_now + num_model_this + 0.5], [stat_all, stat_all], color=color_list[model_class_idx], linestyle='--') rect_grp.append(rc) label_grp.append(f'{stat_name}_all') ax.text(counter_now + num_model_this / 2 + 0.5, stat_all, s='{:.3f}'.format(stat_all), horizontalalignment='center', verticalalignment='bottom', color='black', fontsize='small') if stat_name != stat_ref_name: # this works because CNN model is put first. ax.text(counter_now + num_model_this / 2 + 0.5, stat_all + 0.1, s='{:.1f}%'.format(((stat_all_ref / stat_all) - 1) * 100), horizontalalignment='center', verticalalignment='bottom', color='black', fontsize='x-small', fontweight='bold') counter_now += num_model_this + 1 if ylabel is not None: ax.set_ylabel(ylabel) if title is not None: ax.set_title(title) ax.set_xlim(0, counter_now) ax.set_ylim(0, 1) ax.set_xticks([]) ax.set_yticks(yticks) ax.set_yticklabels(yticklabels) ax.legend(rect_grp, label_grp, loc='best', fontsize='small', ncol=2, columnspacing=0)
def plot_bars(data: pd.Series, ax: Axes) -> Axes: ax.bar(range(len(data.values)), data.values) return ax
def plot_poisson(vals,num,popt,median_p,ax : Axes): x_plot = np.linspace(0, max(vals), num=500) ax.bar(vals,num,alpha=0.5,label='Goal distribution') ax.set_title('Median win probability: '+'%.2f' % median_p) ax.plot(x_plot, poisson(x_plot, *popt), color='red', label='fit') ax.legend()
def plot_confidence( nR_S1: Union[list, np.ndarray], nR_S2: Union[list, np.ndarray], fitModel: Optional[dict] = None, ax: Axes = None, ) -> Axes: """Plot nR_S1 and nR_S2 confidence ratings. Parameters ---------- nR_S1 : 1d array-like Confience ratings (stimuli 1). nR_S2 : 1d array-like Confidence ratings (stimuli 2). fitModel : dict or None Dictionnary returned by :py:funct:`metadpy.std.metad()`. If provided, the estimated ratings will be plotted toghether with the observed data. ax : `Matplotlib.Axes` or None Where to draw the plot. Default is `None` (create a new figure). Returns ------- ax : :class:`matplotlib.axes.Axes` The matplotlib axes containing the plot. Examples -------- """ if fitModel is not None: if isinstance(fitModel, dict): # Retrieve estimate of nRatings for correct and incorrect mu1 = fitModel["meta_da"] / 2 mean_c2 = (fitModel["t2ca_rS2"] + np.abs(np.flip(fitModel["t2ca_rS1"]))) / 2 I_area = 1 - norm.cdf(0, -mu1, 1) C_area = 1 - norm.cdf(0, mu1, 1) allC = np.hstack([0, mean_c2, np.inf]) I_prop_model = (norm.cdf(allC[1:], -mu1, 1) - norm.cdf(allC[:-1], -mu1, 1)) / I_area C_prop_model = (norm.cdf(allC[1:], mu1, 1) - norm.cdf(allC[:-1], mu1, 1)) / C_area else: raise ValueError("You should provided a dictionnary. " "See metadPy.sdt.metad() for help.") if len(nR_S1) != len(nR_S2): raise ValueError("nR_S1 and nR_S2 should have same length") # Get the number of ratings nRratings = int(len(nR_S1) / 2) # Collapse across two stimuli for correct and incorrect responses # this gives flipped corrects followed by incorrects obsCount = nR_S1 + np.flip(nR_S2) C_prop_data = np.flip(obsCount[:nRratings]) / sum(obsCount[:nRratings]) I_prop_data = obsCount[nRratings:] / sum(obsCount[nRratings:]) if ax is None: fig, ax = plt.subplots(1, 1, figsize=(8, 5)) ax.bar( x=np.arange(0.8, nRratings), height=C_prop_data, color="#5f9e6e", width=0.4, ec="k", label="Obs Correct", ) ax.bar( x=np.arange(1.2, nRratings + 0.5), height=I_prop_data, color="#b55d60", width=0.4, ec="k", label="Obs Incorrect", ) if fitModel is not None: ax.plot( np.arange(1.2, nRratings + 0.5), I_prop_model, "o", color="w", markeredgecolor="#b55d60", markersize=16, markeredgewidth=3, label="Est Incorrect", ) ax.plot( np.arange(0.8, nRratings), C_prop_model, "o", color="w", markeredgecolor="#5f9e6e", markersize=16, markeredgewidth=3, label="Est Correct", ) ax.set_ylabel("P$_{(Confidence=y|Outcome)}$") ax.set_xlabel("Confidence level") ax.set_title("Confidence ratings\n and task performances") ax.set_xticks(range(1, nRratings + 1)) return ax
def plot(self, ax: axes.Axes) -> None: if self._frequency != DAILY: return mn, mx = ax.get_ylim() try: if self._notice_signal is not None: first_signal_index = self._quotes.index.get_loc( self._notice_signal) minimum_days_index = self._quotes.index.get_loc( self._notice_signal + timedelta(days=self._notice_to_entry_minimum_days), method="nearest", ) ax.bar( first_signal_index, width=minimum_days_index - first_signal_index, bottom=mn, height=mx - mn, align="edge", color=self._color_notice_stop, alpha=self._alpha, ) if self._prepare_signal is not None: prepare_signal_index = self._quotes.index.get_loc( self._prepare_signal) minimum_days_index = self._quotes.index.get_loc( self._prepare_signal + timedelta(days=self._prepare_minimum_days), method="nearest", ) warning_days_index = self._quotes.index.get_loc( self._prepare_signal + timedelta(days=self._prepare_warning_days), method="nearest", ) ax.bar( prepare_signal_index, width=minimum_days_index - prepare_signal_index, bottom=mn, height=mx - mn, align="edge", color=self._color_prepare_stop, alpha=self._alpha, ) ax.bar( minimum_days_index, width=warning_days_index - minimum_days_index, bottom=mn, height=mx - mn, align="edge", color=self._color_prepare_warning, alpha=self._alpha, ) except KeyError: return