def line(h1: Union[Histogram1D, "HistogramCollection"], ax: Axes, *, errors: bool = False, **kwargs): """Line plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", None) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) kwargs["label"] = kwargs.get("label", h1.name) data = get_data(h1, cumulative=cumulative, density=density) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop("fmt", "-"), ecolor=kwargs.pop("ecolor", "black"), **kwargs) else: ax.plot(h1.bin_centers, data, **kwargs) if show_stats: _add_stats_box(h1, ax, stats=show_stats) if show_values: _add_values(ax, h1, data, value_format=value_format, **text_kwargs)
def _plot_points_to_error_bars_on_ax(self, ax: Axes, x_points: List[float], y_points: List[float], y_err_points: List[float], color: str, label: str = None, y_shift: float = 0, fmt: str = ",", line_width: float = None, alpha: float = None, z_order: float = 1): """ Plot the passed data as a sequence of error bars using standard formatting as configured for this instance. """ if alpha is None: alpha = self.alpha if line_width is None: line_width = self.line_width # TODO: extend this to include x_err too return ax.errorbar(x_points, np.add(y_points, y_shift), yerr=y_err_points, label=label, fmt=fmt, color=color, fillstyle='full', markersize=self.marker_size, capsize=1, ecolor=color, elinewidth=line_width, alpha=alpha, zorder=z_order)
def errorbar(self, *args, **kwargs): """ If the **mantid** projection is chosen, it can be used the same as :py:meth:`matplotlib.axes.Axes.errorbar` for arrays, or it can be used to plot :class:`mantid.api.MatrixWorkspace` or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: import matplotlib.pyplot as plt from mantid import plots ... fig, ax = plt.subplots(subplot_kw={'projection':'mantid'}) ax.errorbar(workspace,'rs',specNum=1) #for workspaces ax.errorbar(x,y,yerr,'bo') #for arrays fig.show() For keywords related to workspaces, see :func:`plotfunctions.errorbar` """ if helperfunctions.validate_args(*args): logger.debug('using plotfunctions') def _data_update(artists, workspace): # errorbar with workspaces can only return a single container container_orig = artists[0] # It is not possible to simply reset the error bars so # we have to plot new lines but ensure we don't reorder them on the plot! orig_idx = self.containers.index(container_orig) container_orig.remove() # The container does not remove itself from the containers list # but protect this just in case matplotlib starts doing this try: self.containers.remove(container_orig) except ValueError: pass # this gets pushed back onto the containers list container_new = plotfunctions.errorbar(self, workspace, **kwargs) self.containers.insert(orig_idx, container_new) self.containers.pop() # update line properties to match original orig_flat, new_flat = cbook.flatten( container_orig), cbook.flatten(container_new) for artist_orig, artist_new in zip(orig_flat, new_flat): artist_new.update_from(artist_orig) # ax.relim does not support collections... self._update_line_limits(container_new[0]) self.autoscale() return container_new workspace = args[0] spec_num = self._get_spec_number(workspace, kwargs) return self.track_workspace_artist(workspace, plotfunctions.errorbar( self, *args, **kwargs), _data_update, spec_num=spec_num) else: return Axes.errorbar(self, *args, **kwargs)
def plot_generic_with_errors(workload: str, metric_y: str, metric_x: str, runs_list: List[Tuple[BenchmarkRun, BenchmarkRun, BenchmarkRun]], ax: Axes): if workload is None: run_tuples = runs_list ax.set_title('all') else: run_tuples = [ run_tuple for run_tuple in runs_list if run_tuple[0].workload == workload ] ax.set_title(workload) xs = [] avg_ys = [] min_ys = [] max_ys = [] for run_tuple in run_tuples: if metric_x in run_tuple[0].thread_config: xs.append(run_tuple[0].thread_config[metric_x]) elif metric_x in run_tuple[1].io_throughput: xs.append(run_tuple[1].io_throughput[metric_y]) # if syscall metric: "<NAME-METRIC>" else: syscall_name, syscall_metric = metric_x.split('-') sm = [ metrics for metrics in run_tuple[1].syscall_metrics if metrics.name == syscall_name ][0] xs.append(vars(sm)[syscall_metric]) # runtime or latency min_ys.append(vars(run_tuple[0])[metric_y]) avg_ys.append(vars(run_tuple[1])[metric_y]) max_ys.append(vars(run_tuple[2])[metric_y]) y_upper_errors = [abs(pair[0] - pair[1]) for pair in zip(avg_ys, max_ys)] y_lower_errors = [abs(pair[0] - pair[1]) for pair in zip(avg_ys, min_ys)] ax.errorbar(xs, avg_ys, yerr=[y_lower_errors, y_upper_errors], color='tab:blue') ax.tick_params(axis='y', labelcolor='tab:blue') ax.set_xlabel(metric_x) ax.set_ylabel(metric_y) ax.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
def errorbar(self, *args, **kwargs): """ If the **mantid** projection is chosen, it can be used the same as :py:meth:`matplotlib.axes.Axes.errorbar` for arrays, or it can be used to plot :class:`mantid.api.MatrixWorkspace` or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: import matplotlib.pyplot as plt from mantid import plots ... fig, ax = plt.subplots(subplot_kw={'projection':'mantid'}) ax.errorbar(workspace,'rs',specNum=1) #for workspaces ax.errorbar(x,y,yerr,'bo') #for arrays fig.show() For keywords related to workspaces, see :func:`plotfunctions.errorbar` """ if helperfunctions.validate_args(*args): logger.debug('using plotfunctions') def _data_update(artists, workspace): # errorbar with workspaces can only return a single container container_orig = artists[0] # It is not possible to simply reset the error bars so # we have to plot new lines but ensure we don't reorder them on the plot! orig_idx = self.containers.index(container_orig) container_orig.remove() # The container does not remove itself from the containers list # but protect this just in case matplotlib starts doing this try: self.containers.remove(container_orig) except ValueError: pass # this gets pushed back onto the containers list container_new = plotfunctions.errorbar(self, workspace, **kwargs) self.containers.insert(orig_idx, container_new) self.containers.pop() # update line properties to match original orig_flat, new_flat = cbook.flatten(container_orig), cbook.flatten(container_new) for artist_orig, artist_new in zip(orig_flat, new_flat): artist_new.update_from(artist_orig) # ax.relim does not support collections... self._update_line_limits(container_new[0]) self.autoscale() return container_new workspace = args[0] spec_num = self._get_spec_number(workspace, kwargs) return self.track_workspace_artist(workspace, plotfunctions.errorbar(self, *args, **kwargs), _data_update, spec_num=spec_num) else: return Axes.errorbar(self, *args, **kwargs)
def scatter_with_err_bar( xs: NumArray, ys: NumArray, xerr: NumArray = None, yerr: NumArray = None, ax: Axes = None, xlabel: str = "Actual", ylabel: str = "Predicted", title: str = None, **kwargs: Any, ) -> Axes: """Scatter plot with optional x- and/or y-error bars. Useful when passing model uncertainties as yerr=y_std for checking if uncertainty correlates with error, i.e. if points farther from the parity line have larger uncertainty. Args: xs (array): x-values ys (array): y-values xerr (array, optional): Horizontal error bars. Defaults to None. yerr (array, optional): Vertical error bars. Defaults to None. ax (Axes, optional): matplotlib Axes on which to plot. Defaults to None. xlabel (str, optional): x-axis label. Defaults to "Actual". ylabel (str, optional): y-axis label. Defaults to "Predicted". title (str, optional): Plot tile. Defaults to None. Returns: ax: The plot's matplotlib Axes. """ if ax is None: ax = plt.gca() styles = dict(markersize=6, fmt="o", ecolor="g", capthick=2, elinewidth=2) ax.errorbar(xs, ys, yerr=yerr, xerr=xerr, **kwargs, **styles) # identity line ax.axline((0, 0), (1, 1), alpha=0.5, zorder=0, linestyle="dashed", color="black") add_mae_r2_box(xs, ys, ax) ax.set(xlabel=xlabel, ylabel=ylabel, title=title) return ax
def plot_static(results: list[StaticResult], ax: Axes, ylim_top: float, ylim_bottom: float): assert len({res.static_run.workload for res in results}) == 1 if not len({res.static_run.static_size for res in results}) == len(results): print([(res.static_run.static_size, res.static_run.workload.description()) for res in results]) assert False xs = [] ys = [] stddvs = [] for res in results: xs.append(res.static_run.static_size) ys.append(res.runtime_seconds) stddvs.append(res.std_deviation) ax.errorbar(xs, ys, yerr=stddvs, color='tab:blue', capsize=3) ax.tick_params(axis='y', labelcolor='tab:blue') ax.set_xlabel('pool size') ax.set_ylabel('runtime in seconds') ax.set_ylim(top=ylim_top, bottom=ylim_bottom) ax.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
def plot_lines(axes: Axes, data, linestyle='solid', stde=None): """ plot dataframe columns onto pyplot axes. each column is plotted using a seperate command with specific properties assigned to it (color, marker, linestyle, etc.). :parameter axes(): the axes where data will be plotted. data(DataFrame): time series. stnd_error(DataFrame): standard error of data with same shape as data. label(string): a string designating what kind of data is being ploted. for purpose of assigning a line style. can be one of 'control', 'treatment' or 'normalized' :returns lines(dict): keys = names of data columns. values = pyplot line objects. """ # turn index 'days' into first column data.reset_index(inplace=True) x_data = data['days'] lines = {} i = 0 for soil in SOILS: i += 1 y_data = data[soil] y_error = stde[soil] if stde is not None else None line = axes.errorbar( x_data, y_data, ls=LINE_STYLES[linestyle], yerr=y_error, label=soil, color=COLORS[soil], marker=MARKERS[soil], ) lines[soil] = line return lines
def draw_subplot(*, subplot: Axes, xlabel: str = None, ylabel: str, xlim: Tuple[float, float] = (6, 19), ylim: Tuple[float, float] = (-150, 150), x_line: pd.Series, y_line: pd.Series, yerr: pd.Series, marker: str = 's', markersize: float = 3., line_color: str = 'k', capsize: float = 5., linewidth: float = 1., x_scatter: pd.Series, y_scatter: pd.Series, scatter_color: str = 'gray', scatter_point_size: float = 1., ratio: float = 7 / 13) -> None: subplot.set(xlabel=xlabel, ylabel=ylabel, xlim=xlim, ylim=ylim) subplot.errorbar(x=x_line, y=y_line, yerr=yerr, marker=marker, markersize=markersize, color=line_color, capsize=capsize, linewidth=linewidth) subplot.scatter(x=x_scatter, y=y_scatter, color=scatter_color, s=scatter_point_size) subplot.minorticks_on() subplot.xaxis.set_ticks_position('both') subplot.yaxis.set_ticks_position('both') subplot.set_aspect(ratio / subplot.get_data_ratio())
def scatter(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs): """Scatter plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) value_format = kwargs.pop("value_format", None) text_kwargs = pop_kwargs_with_prefix("text_", kwargs) label = kwargs.pop("label", h1.name) data = get_data(h1, cumulative=cumulative, density=density) if "cmap" in kwargs: cmap = _get_cmap(kwargs) _, cmap_data = _get_cmap_data(data, kwargs) kwargs["color"] = cmap(cmap_data) elif "color" in kwargs or "c" in kwargs: kwargs["color"] = kwargs.pop("color", kwargs.get("c", None)) _apply_xy_lims(ax, h1, data, kwargs) _add_ticks(ax, h1, kwargs) _add_labels(ax, h1, kwargs) if errors: err_data = get_err_data(h1, cumulative=cumulative, density=density) ax.errorbar(h1.bin_centers, data, yerr=err_data, fmt=kwargs.pop("fmt", "o"), ecolor=kwargs.pop("ecolor", "black"), ms=0) ax.scatter(h1.bin_centers, data, label=label, **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 _make_deconvolved_mse_plot(ax: Axes, deconvolved_grid: deconvolvers.LRFisterGrid): """Plot deconvolved MSE vs regularization strength Parameters: ----------- ax: matplotlib.axes.Axes Axis to plot on deconvolved_grid: deconvolvers.LRFisterGrid Fitted instance of LRFisterGrid """ line = ax.errorbar( deconvolved_grid.regularization_strengths, deconvolved_grid.deconvolved_mse_, deconvolved_grid.deconvolved_mse_std_, ) min_ind = np.argmin(deconvolved_grid.deconvolved_mse_) ax.plot( deconvolved_grid.regularization_strengths[min_ind], deconvolved_grid.deconvolved_mse_[min_ind], marker="x", color=line[0].get_color(), )
def plot_adaptive(results: list[AdapterResult], ax: Axes, ylim_top: float, ylim_bottom: float): assert len({res.adapter_run.workload for res in results}) == 1 if not len({res.adapter_run.adapter_config for res in results}) == len(results): print([res.adapter_run.adapter_config for res in results]) assert False xs = [] ys = [] y2s = [] stddvs = [] results = sorted( results, key=lambda x: x.adapter_run.adapter_config.short_description()) for res in results: xs.append(res.adapter_run.adapter_config.short_description()) ys.append(res.runtime_seconds) y2s.append(res.avg_pool_size) stddvs.append(res.std_deviation) p1 = ax.errorbar(xs, ys, yerr=stddvs, color='tab:blue', capsize=3, label='runtime') ax.tick_params(axis='y', labelcolor='tab:blue') ax.set_xlabel('adapter config') ax.set_ylabel('runtime in seconds') ax.set_ylim(top=ylim_top, bottom=ylim_bottom) ax.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5) ax2 = ax.twinx() p2 = ax2.plot(xs, y2s, 'r-', label='avg pool size') ax2.set_ylabel('avg pool size')
def errorbar(self, *args, **kwargs): ''' If the **mantid** projection is chosen, it can be used the same as :py:meth:`matplotlib.axes.Axes.errorbar` for arrays, or it can be used to plot :class:`mantid.api.MatrixWorkspace` or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: import matplotlib.pyplot as plt from mantid import plots ... fig, ax = plt.subplots(subplot_kw={'projection':'mantid'}) ax.errorbar(workspace,'rs',specNum=1) #for workspaces ax.errorbar(x,y,yerr,'bo') #for arrays fig.show() For keywords related to workspaces, see :func:`mantid.plots.plotfunctions.errorbar` ''' if mantid.plots.helperfunctions.validate_args(*args): mantid.kernel.logger.debug('using mantid.plots.plotfunctions') return mantid.plots.plotfunctions.errorbar(self, *args, **kwargs) else: return Axes.errorbar(self, *args, **kwargs)
def errorbar(self, *args, **kwargs): from mslice.cli.plotfunctions import errorbar if is_cut(*args): return errorbar(self, *args, **kwargs) else: return Axes.errorbar(self, *args, **kwargs)
def plot_rms_with_error_to_ax(ax: Axes, data_object_list: DataObjectList, pixel_width=None, label_list: Union[str, list[str]] = None, title: Optional[str] = "", average_n: int = 8, x_units: Literal["px", "µm", "nm"] = "µm", y_units: Literal["µm", "nm"] = "µm", plotter_style: PlotterStyle = None): """ Plot a diagram to ax, showing the root mean square roughness per column in for data in data_object_list. The error-bars are calculated as standard deviation of columns (average_n) used per data point. :param ax: Axes object to which the surface should be written :param data_object_list: DataObjectList :param pixel_width: Pixel width/height in [m] (only used, if data_object has no pixel_width attribute) :param label_list: List with labels (str) for legend entries. If data_object_list is a dict, the keys are used. :param average_n: Number of columns to average over :param x_units: unit for x-axis (µm or nm) :param y_units: :param plotter_style: PlotterStyle to format Figure-object (default: None -> use default format) :return: None """ ndarray2d_list, pixel_width_list, label_list, x_units = _get_ax_data_lists( data_object_list, pixel_width=pixel_width, label_list=label_list, x_units=x_units) pixel_width_list, x_units = _check_pixel_width_list( pixel_width_list, x_units) x_factor, x_unit_label = unit_factor_and_label(x_units) y_factor, y_unit_label = unit_factor_and_label(y_units) plotter_style = _copy_plotter_style(plotter_style, default=get_plotter_style_sigma) plotter_style.set(x_unit=x_unit_label, y_unit=y_unit_label, ax_title=title) graph_styler = plotter_style.graph_styler.reset() plotter_style.set_format_to_ax(ax) for i, data in enumerate(ndarray2d_list): z_data = data # get mu for every column first: sigma_col_list = [] for j in range(0, z_data.shape[1]): _, sigma_col = get_mu_sigma(z_data[:, j:j + 1]) sigma_col_list.append(sigma_col) x_pos = [] y_rms = [] y_error = [] pixel_width = pixel_width_list[i] * x_factor for j in range(0, z_data.shape[1] - average_n, average_n): # step): x_pos.append((j + max(average_n - 1, 0) / 2.0) * pixel_width) mu_rms, sigma_rms = get_mu_sigma( np.array(sigma_col_list[j:j + average_n])) y_rms.append(mu_rms * y_factor) y_error.append(sigma_rms * y_factor) style_dict = { "fmt": 'o', "elinewidth": 0.6, "capsize": 2.0, "markersize": 5, "color": graph_styler.dict["color"] } ax.errorbar( x_pos, y_rms, yerr=y_error, label=label_list[i], **style_dict ) # **graph_styler.dict, label=key) #fmt='-o') # **graph_styler.dict graph_styler.next_style() # ax_rms.set_title(f"window width = {moving_average_n*pixel_width_in_um:.1f}") if any(label for label in label_list if label is None): ax.legend() ax.legend()
def errorbar(self, *args, **kwargs): """ If the **mantid** projection is chosen, it can be used the same as :py:meth:`matplotlib.axes.Axes.errorbar` for arrays, or it can be used to plot :class:`mantid.api.MatrixWorkspace` or :class:`mantid.api.IMDHistoWorkspace`. You can have something like:: import matplotlib.pyplot as plt from mantid import plots ... fig, ax = plt.subplots(subplot_kw={'projection':'mantid'}) ax.errorbar(workspace,'rs',specNum=1) #for workspaces ax.errorbar(x,y,yerr,'bo') #for arrays fig.show() For keywords related to workspaces, see :func:`plotfunctions.errorbar` """ if helperfunctions.validate_args(*args): logger.debug('using plotfunctions') autoscale_on_update = kwargs.pop("autoscale_on_update", True) def _data_update(artists, workspace, new_kwargs=None): if self.lines: self.set_autoscaley_on(autoscale_on_update) # errorbar with workspaces can only return a single container container_orig = artists[0] # It is not possible to simply reset the error bars so # we have to plot new lines but ensure we don't reorder them on the plot! orig_idx = self.containers.index(container_orig) container_orig.remove() # The container does not remove itself from the containers list # but protect this just in case matplotlib starts doing this try: self.containers.remove(container_orig) except ValueError: pass # this gets pushed back onto the containers list if new_kwargs: container_new = plotfunctions.errorbar(self, workspace, **new_kwargs) else: container_new = plotfunctions.errorbar(self, workspace, **kwargs) self.containers.insert(orig_idx, container_new) self.containers.pop() # Update joining line if container_new[0] and container_orig[0]: container_new[0].update_from(container_orig[0]) # Update caps for orig_caps, new_caps in zip(container_orig[1], container_new[1]): new_caps.update_from(orig_caps) # Update bars for orig_bars, new_bars in zip(container_orig[2], container_new[2]): new_bars.update_from(orig_bars) # Re-plotting in the config dialog will assign this attr if hasattr(container_orig, 'errorevery'): setattr(container_new, 'errorevery', container_orig.errorevery) # ax.relim does not support collections... self._update_line_limits(container_new[0]) self.set_autoscaley_on(True) return container_new workspace = args[0] spec_num = self.get_spec_number(workspace, kwargs) is_normalized, kwargs = get_normalize_by_bin_width(workspace, self, **kwargs) if self.lines: self.set_autoscaley_on(autoscale_on_update) artist = self.track_workspace_artist( workspace, plotfunctions.errorbar(self, *args, **kwargs), _data_update, spec_num, is_normalized) self.set_autoscaley_on(True) return artist else: return Axes.errorbar(self, *args, **kwargs)