def plot_histogram(axes: mpl.axes.Axes, hist, popt, bin_edges: np.ndarray, axis: str): """ plots the histogram of one of the axis projections Plot the projection of histogram of hits. The plot is plotted vertically if the axis label is given as 'y' Parameters ---------- axes : mpl.axes.Axes the axes to plot the histogram into. The plot will be vertical if the axis is specified to be 'y' hist : np.ndarray the histogramd hits popt : np.ndarray the parameters for the Gaussian that to be plotted over the hist bin_edges : np.ndarray the edges of the bins used for the histogram axis : str the axis on for which the results should be plotted (either 'x' or 'y'). Plots vertically if 'y' is specified. """ bin_centers = (bin_edges[1:] + bin_edges[:-1])/2 if axis == 'x': axes.set_xlim([bin_edges[0], bin_edges[-1]]) axes.hist(bin_edges[:-1], bin_edges, weights=hist, density=True) axes.plot(bin_centers, norm.pdf(bin_centers, *popt)) elif axis == 'y': axes.set_ylim([bin_edges[0], bin_edges[-1]]) axes.hist(bin_edges[:-1], bin_edges, weights=hist, density=True, orientation='horizontal') axes.plot(norm.pdf(bin_centers, *popt), bin_centers) else: raise ValueError("axis has to be either 'x' or 'y'")
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 plot_mesh(ax: matplotlib.axes.Axes, xe: numpy.ndarray, ye: numpy.ndarray, scale: float = 1000) -> None: """ Add a mesh to a plot. Arguments --------- ax : matplotlib.axes.Axes Axes object in which to add the mesh. xe : numpy.ndarray M x 2 array of begin/end x-coordinates of mesh edges. ye : numpy.ndarray M x 2 array of begin/end y-coordinates of mesh edges. scale : float Indicates whether the axes are in m (1) or km (1000). """ xe1 = xe[:, (0, 1, 1)] / scale xe1[:, 2] = numpy.nan xev = xe1.reshape((xe1.size, )) ye1 = ye[:, (0, 1, 1)] / scale ye1[:, 2] = numpy.nan yev = ye1.reshape((ye1.size, )) # to avoid OverflowError: In draw_path: Exceeded cell block limit # plot the data in chunks ... for i in range(0, len(xev), 3000): ax.plot(xev[i:i + 3000], yev[i:i + 3000], color=(0.5, 0.5, 0.5), linewidth=0.25)
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 visualize_records(axs : matplotlib.axes.Axes, record : Record): previous = record.records[0] for current in record.records[1:]: xs = [previous[0], current[0]] ys = [previous[1], current[1]] previous = current axs.plot(xs, ys, color='black', linewidth=2.0)
def plot_modes(self, ax: matplotlib.axes.Axes, n: int = 0, iq: int = 0): '''Plotting the phonon modes and its derivatives :param ax: :param n: the order of derivatives to be plotted: :math:`n = 0` for :math:`\\omega_{qm}(V)`, :math:`n = 1` for :math:`\\gamma_{qm}(V)`, :math:`n = 2` for :math:`V\\frac{\partial\gamma_{qm}(V)}{\partial V}` :param iq: the index of :math:`q` point to be plotted ''' if n == 0: w_arrays = self.calculator.freq_array[:, iq, :] elif n == 1: w_arrays = self.calculator.mode_gamma[0][:, iq, :] elif n == 2: w_arrays = self.calculator.mode_gamma[1][:, iq, :] for k in range(self.calculator.np): if iq == 0 and k < 3: continue w_array = w_arrays[:, k] ax.plot(self.v_array, w_array) if n != 0: return for k in range(self.calculator.np): if iq == 0 and k < 3: continue freqs = numpy.array([ volume.q_points[iq].modes[k] for volume in self.qha_input.volumes ]) ax.scatter(self.volumes, freqs, s=10)
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_loss(ax: matplotlib.axes.Axes, training_losses: list, validation_losses: list): sz = len(training_losses) ax.plot(range(sz), training_losses, c='r', label='t--' + str(training_losses[-1])) ax.plot(range(sz), validation_losses, c='g', label='v--' + str(validation_losses[-1])) # ax.legend(fontsize=16) ax.grid(alpha=0.25)
def visualize_mesh(axs : matplotlib.axes.Axes, mesh : Mesh): for t in mesh.tInd: verts = [mesh.verts[i] for i in t] xs = [v[0] for v in verts] xs.append(xs[0]) ys = [v[1] for v in verts] ys.append(ys[0]) axs.plot(xs, ys, color='black', linewidth=0.5)
def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None: """Draw plot of TIC on ax""" super().plot(ax, back_color) dataset = f"ms1_{self.polarity[:3]}" tic_df = get_bpc(self.h5_file_name, dataset=dataset, integration="tic") ax.plot(tic_df["rt"], tic_df["i"]) ax.xaxis.set_minor_locator(MultipleLocator(1))
def show_x_balanced(self, ax: matplotlib.axes.Axes, func: Func) -> None: x = self._x y = func.f(x) ax.plot([x], [y], color='blue', marker='o') half = self._deltax / 2.0 x0 = x - half y0 = func.f(x0) x1 = x + half y1 = func.f(x1) ax.plot([x0, x1], [y0, y1], color='red', marker='o')
def _draw_curve(self, ax: matplotlib.axes.Axes, rt_buffer: float) -> None: """Draw the EIC data and fill under the curve betweeen RT min and RT max""" eic = self.compound["data"]["eic"] if eic is not None and "rt" in eic and len(eic["rt"]) > 0: # fill_between requires a data point at each end of range, so add points via interpolation x, y = add_interp_at(eic["rt"], eic["intensity"], self.rt_range) ax.plot(x, y) utils.fill_under(ax, x, y, between=self.rt_range, color="c", alpha=0.3) x_min = min(self.rt_range[0], self.rt_peak) - rt_buffer x_max = max(self.rt_range[1], self.rt_peak) + rt_buffer ax.set_xlim(x_min, x_max)
def hstripe(ax: mpl.axes.Axes, x: np.ndarray, labels: List[str] = None, limit: int = None, plot_kwargs: Dict[str, Any] = {}) -> None: """ Plots a horizontal stripe plot in the given axis. Parameters === ax : matplotlib.axes.Axes The axis to add the plot to. x : numpy.ndarray An array of shape (n_classes, 3) where: x[:, 0] is the lower bounds x[:, 1] is the midpoints x[:, 2] is the upper bounds labels : list A list containing `n_classes` labels. Default: class indices are used. limit : int Limits the number of data points displayed; the middle data points are skipped. Default: all data points plotted. plot_kwargs : dict Keyword arguments passed to the plot. """ num_rows = x.shape[0] labels = labels if labels is not None else list(range(num_rows)) # Combine default and custom kwargs # TODO: @rloganiv - find a clearner way to merge dictionaries _plot_kwargs = DEFAULT_PLOT_KWARGS.copy() _plot_kwargs.update(plot_kwargs) # Apply limit sentinel = np.empty((1, 3)) sentinel[:] = np.nan if limit is not None: x = np.concatenate((x[:limit], sentinel, x[-limit:]), axis=0) labels = labels[:limit] + ['...'] + labels[-limit:] num_rows = x.shape[0] # Plot for i, row in enumerate(x): low, mid, high = row.tolist() ax.plot((low, high), (i, i), **_plot_kwargs) ax.plot((mid, mid), (i - .2, i + .2), **_plot_kwargs) # Add labels ax.set_ylim(-1, num_rows) ax.set_yticks(np.arange(num_rows)) ax.set_yticklabels(labels) ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
def plot_p_and_q(self, ax: mpl.axes.Axes): """Plot p(x) and q(x) for Sturm-Liouville models. Plots both learned and true coefficients, if true coefficients are provided to the Plotter constructor. Keyword arguments ax -- matplotlib.axes.Axes to plot on """ # Throw an error if using this for a non-Sturm-Liouville operator if not self.is_sturm_liouville: Exception("This method only applies to Sturm-Liouville operators.") # Pull out the parametric coefficient for 'f' learned_f_coeff = self.reg_coeffs['f'] # Compute learned parametric coefficient \phi inferred_phi = -1*np.reciprocal(learned_f_coeff) # Set NaN entries to 0 (shouldn't be any NaNs though...) inferred_phi[np.isnan(inferred_phi)] = 0 # Save the inferred phi vector self.inferred_phi = inferred_phi # If it is p(x), call it that on the line label if self.lhs_term == 'd^{2}u/dx^{2}': phi_label = "Inferred p(x)" elif self.lhs_term == 'd^{4}u/dx^{4}': phi_label = "Inferred p(x)" else: phi_label = "Inferred $\phi(x)$" # So plot against the true p(x) p_x_plotted = self.p_x-np.mean(self.p_x) ax.plot(self.true_x_vector, p_x_plotted, color=self.coeff_colors[0], label='True $p(x)$', **self.true_opts) # for S-L, u_xx (or u_xxxx) regression, phi(x) is p(x) ip = inferred_phi-np.mean(self.p_x) ax.plot(self.reg_x_vector, ip, marker=self.markers[0], markevery=self.npts, label=phi_label, **self.reg_opts) # If 'u' is found in the model, there is a q(x) that can be computed if 'u' in self.reg_coeffs: # Compute q(x) inferred_q = self.reg_coeffs['u'] * inferred_phi # Plot true and inferred q on a new axis offset = max([ceil(max(p_x_plotted)+abs(min(self.q_x))), 1]) # Plot true and inferred q iq = self.q_x-np.mean(self.q_x)+offset ax.plot(self.true_x_vector, iq, color=self.coeff_colors[1], label="True $q(x)$", **self.true_opts) ax.plot(self.reg_x_vector, inferred_q-np.mean(self.q_x)+offset, marker=self.markers[1], label="Inferred $q(x)$", markevery=self.npts, **self.reg_opts) # Save the inferred q(x) self.inferred_q = inferred_q # Throw a legend on this if self.show_legends: leglines = ax.get_lines() leglabels = [l.get_label() for l in leglines] ax.legend(leglines, leglabels, **self.legend_opts)
def draw_faces(vertices: np.ndarray, faces: np.ndarray, ax: mpl.axes.Axes): "Draw faces of cell decomposition of sphere" colors = plt.get_cmap('tab20').colors all_polys = [] for i in range(len(faces)): xyz = vertices[faces[i]] # xyz = faces_points[i, :, :] ax.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], c='k', alpha=0.0) all_polys.append(xyz.tolist()) p3d = Poly3DCollection(all_polys) p3d.set_color(colors[1]) p3d.set_edgecolor('k') p3d.set_alpha(1.0) ax.add_collection3d(p3d)
def quantile_plot( ax: matplotlib.axes.Axes, x: np.ndarray, median: np.ndarray, lower: np.ndarray, upper: np.ndarray, shaded_kwargs: Dict[str, Any], line_kwargs: Dict[str, Any]) -> List[matplotlib.lines.Line2D]: """Create mean +- sd plot.""" ax.fill_between(x, lower, upper, **shaded_kwargs) return ax.plot(x, median, **line_kwargs)
def plot_ode_solutions(self, ax: mpl.axes.Axes, number: int = 3, start_idc: int = 0, shift: int = 0): """Plot solutions to differential equations used to build dataset. Keyword arguments ax -- matplotlib.axes.Axes to plot on ode_sols -- list of diff eqn solutions from scipy's solve_ivp number -- plot only the first <number> solutions in the ode_sols list start_idc -- instead of retrieving the first <number> solutions to plot start retrieval at the start_idc index of the list shift -- provide x-axis offset to each successive solution plotted. useful if the solutions overlap significantly. """ # ODE line colors and line properties ode_sols = self.ode_sols lcolors = self.ode_colors lprops = self.ode_opts # Plot differential equation solutions num_sols_to_plot = min(len(ode_sols), number) lines = [] # Plot each ODE solution for i in range(num_sols_to_plot): sol = ode_sols[i+start_idc] label_u = self.dependent_var + ' solution {}'.format(i+1) label_dudx = 'd{}/d{}, solution {}'.format(self.dependent_var, self.independent_var, i+1) if i < len(lcolors): line, = ax.plot(sol.t+(i*shift), sol.y[0], color=lcolors[i], linestyle='-', label=label_u, **lprops) dline, = ax.plot(sol.t+(i*shift), sol.y[1], color=lcolors[i], linestyle='--', label=label_dudx, **lprops) else: line, = ax.plot(sol.t+(i*shift), sol.y[0], linestyle='-', label=label_u, **lprops) dline, = ax.plot(sol.t+(i*shift), sol.y[1], color=line.get_color(), linestyle='--', label=label_dudx, **lprops) lines.append(line) lines.append(dline) # Format the plot title, x-axis label, y-axis label, and legend if self.show_legends: leg_lines = [lines[0], lines[1]] leg_labels = ['u', '$du/dx$'] ax.legend(leg_lines, leg_labels, **self.legend_opts)
def spm_plot(ax: matplotlib.axes.Axes, x: np.ndarray, spm_test: _SPM0Dinference, shaded_kwargs: Dict[str, Any], line_kwargs: Dict[str, Any]) -> List[matplotlib.lines.Line2D]: """Create SPM plot.""" ax.axhline(spm_test.zstar, ls='--', color='grey') ax.axhline(-spm_test.zstar, ls='--', color='grey') ax.fill_between(x, spm_test.zstar, spm_test.z, where=(spm_test.z > spm_test.zstar), **shaded_kwargs) ax.fill_between(x, -spm_test.zstar, spm_test.z, where=(spm_test.z < -spm_test.zstar), **shaded_kwargs) return ax.plot(x, spm_test.z, **line_kwargs)
def plot_portfolio(r: pd.DataFrame, tag: str, ax2: matplotlib.axes.Axes): """ Ploduce plots of portfolio holding Parameters ---------- r: pd.DataFrame Dataframe containing the variables tag: str Name of the algorithm to plot result ax2: matplotlib.axes.Axes Axes to draw in """ ax2.plot(r["NextHolding_{}".format(tag)].values[1:-1], label=tag) ax2.plot(r["OptNextHolding"].values[1:-1], label="benchmark", alpha=0.5)
def plot_BestDQNActions( p: dict, model, holding: float, ax: matplotlib.axes.Axes = None ): """ Ploduce plots of learned action-value function of DQN Parameters ---------- p: dict Parameter passed as config files model Loaded model holding: float Fixed holding at which we produce the value function plot ax: matplotlib.axes.Axes Axes to draw in """ if not p["zero_action"]: actions = np.arange(-p["KLM"][0], p["KLM"][0] + 1, p["KLM"][1]) actions = actions[actions != 0] else: actions = np.arange(-p["KLM"][0], p["KLM"][0] + 1, p["KLM"][1]) sample_Ret = np.linspace(-0.05, 0.05, 100) if holding == 0: holdings = np.zeros(len(sample_Ret)) else: holdings = np.ones(len(sample_Ret)) * holding states = tf.constant( np.hstack((sample_Ret.reshape(-1, 1), holdings.reshape(-1, 1))), dtype=tf.float32, ) pred = model(states, training=False) max_action = actions[tf.math.argmax(pred, axis=1)] ax.plot(sample_Ret, max_action, linewidth=1.5)
def plot_trajectory( ax: matplotlib.axes.Axes, az: np.ndarray, alt: np.ndarray, color: Optional[str] = None, label: Optional[str] = None, ) -> None: """Plot a curve with an arrow indicating direction of motion.""" line = ax.plot(np.radians(az), 90.0 - alt, color=color, label=label)[0] add_arrow(line)
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_topk_cost(ax: mpl.axes.Axes, experiment_name: str, eval_metric: str, pool_size: int, plot_kwargs: Dict[str, Any] = {}) -> None: """ Replicates Figure 2 in [CITE PAPER]. Parameters === experiment_name: str. Experimental results were written to files under a directory named using experiment_name. eval_metric: str. Takes value from ['avg_num_agreement', 'mrr'] pool_size: int. Total size of pool from which samples were drawn. plot_kwargs : dict. Keyword arguments passed to the plot. Returns === fig, axes : The generated matplotlib Figure and Axes. """ _plot_kwargs = DEFAULT_PLOT_KWARGS.copy() _plot_kwargs.update(plot_kwargs) for method in COST_METHOD_NAME_DICT: metric_eval = np.load( RESULTS_DIR + experiment_name + ('/%s_%s_top1_pseudocount1.0.npy' % (method, eval_metric))) x = np.arange(len(metric_eval)) * LOG_FREQ / pool_size ax.plot(x, metric_eval, label=COST_METHOD_NAME_DICT[method], **_plot_kwargs) cutoff = len(metric_eval) - 1 ax.set_xlim(0, cutoff * LOG_FREQ / pool_size) ax.set_ylim(0, 1.0) xmin, xmax = ax.get_xlim() step = ((xmax - xmin) / 4.0001) ax.xaxis.set_major_formatter(ticker.PercentFormatter(xmax=1)) ax.xaxis.set_ticks(np.arange(xmin, xmax + 0.001, step)) ax.yaxis.set_ticks(np.arange(0, 1.01, 0.20)) ax.tick_params(pad=0.25, length=1.5) return ax
def err_plot(x, y, yerr=None, xerr=None, axis: mpl.axes.Axes = None, **mpl_args): """Plot graph with error bars. Decided weather to plot points with error bars or lines with shaded areas depending on the number of plotted points. Parameters ---------- x, y : array_like x and y coordinates of the data to plot. yerr, xerr : array_like, optional The corresponding error of the data. Has same shape `x` and `y`. axis : mpl.axes.Axes, optional `mpl.axes.Axes` object used for plotting. mpl_args : Arguments for plotting passed to `axis.errorbar` or `axis.plot`. """ axis = plt.gca() if axis is None else axis x = np.asarray(x) if x.size > 50: # continuous plot try: ecolor = mpl_args.pop('ecolor') except KeyError: # no color defined -> try color else default ecolor = mpl_args.get('color', None) try: fmt = mpl_args.pop('fmt') except KeyError: baseline, = axis.plot(x, y, **mpl_args) else: baseline, = axis.plot(x, y, fmt, **mpl_args) if ecolor is None: ecolor = baseline.get_color() if yerr is not None: axis.fill_between(x, y-yerr, y+yerr, color=ecolor, alpha=.3, zorder=1) if xerr is not None: axis.fill_betweenx(y, x-xerr, x+xerr, color=ecolor, alpha=.3, zorder=1) else: default_args = {'capsize': 2.5, 'elinewidth': .3} default_args.update(mpl_args) axis.errorbar(x, y, yerr=yerr, **default_args)
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_data(ax: mpl.axes.Axes, data: PlotData) -> Optional[List[mpl.lines.Line2D]]: x, y = None, None lines = None # Return line objects so we can add legends disp = data.display_attributes if isinstance(data, XYData) or isinstance(data, TimeSeries): x, y = (data.x, data.y) if isinstance(data, XYData) else (np.arange(len(data.timestamps)), data.values) if isinstance(disp, LinePlotAttributes): lines, = ax.plot(x, y, linestyle=disp.line_type, linewidth=disp.line_width, color=disp.color) if disp.marker is not None: # type: ignore ax.scatter(x, y, marker=disp.marker, c=disp.marker_color, s=disp.marker_size, zorder=100) elif isinstance(disp, ScatterPlotAttributes): lines = ax.scatter(x, y, marker=disp.marker, c=disp.marker_color, s=disp.marker_size, zorder=100) elif isinstance(disp, BarPlotAttributes): lines = ax.bar(x, y, color=disp.color) # type: ignore elif isinstance(disp, FilledLinePlotAttributes): x, y = np.nan_to_num(x), np.nan_to_num(y) pos_values = np.where(y > 0, y, 0) neg_values = np.where(y < 0, y, 0) ax.fill_between(x, pos_values, color=disp.positive_color, step='post', linewidth=0.0) ax.fill_between(x, neg_values, color=disp.negative_color, step='post', linewidth=0.0) else: raise Exception(f'unknown plot combination: {type(data)} {type(disp)}') # For scatter and filled line, xlim and ylim does not seem to get set automatically if isinstance(disp, ScatterPlotAttributes) or isinstance(disp, FilledLinePlotAttributes): xmin, xmax = _adjust_axis_limit(ax.get_xlim(), x) if not np.isnan(xmin) and not np.isnan(xmax): ax.set_xlim((xmin, xmax)) ymin, ymax = _adjust_axis_limit(ax.get_ylim(), y) if not np.isnan(ymin) and not np.isnan(ymax): ax.set_ylim((ymin, ymax)) elif isinstance(data, TradeSet) and isinstance(disp, ScatterPlotAttributes): lines = ax.scatter(np.arange(len(data.timestamps)), data.values, marker=disp.marker, c=disp.marker_color, s=disp.marker_size, zorder=100) elif isinstance(data, TradeBarSeries) and isinstance(disp, CandleStickPlotAttributes): draw_candlestick(ax, np.arange(len(data.timestamps)), data.o, data.h, data.l, data.c, data.v, data.vwap, colorup=disp.colorup, colordown=disp.colordown) elif isinstance(data, BucketedValues) and isinstance(disp, BoxPlotAttributes): draw_boxplot( ax, data.bucket_names, data.bucket_values, disp.proportional_widths, disp.notched, # type: ignore disp.show_outliers, disp.show_means, disp.show_all) # type: ignore elif isinstance(data, XYZData) and (isinstance(disp, SurfacePlotAttributes) or isinstance(disp, ContourPlotAttributes)): display_type: str = 'contour' if isinstance(disp, ContourPlotAttributes) else 'surface' draw_3d_plot(ax, data.x, data.y, data.z, display_type, disp.marker, disp.marker_size, disp.marker_color, disp.interpolation, disp.cmap) else: raise Exception(f'unknown plot combination: {type(data)} {type(disp)}') return lines
def chainage_markers(xykm: numpy.ndarray, ax: matplotlib.axes.Axes, ndec: int = 1, scale: float = 1000) -> None: """ Add markers indicating the river chainage to a plot. Arguments --------- xykm : numpy.ndarray Array containing the x, y, and chainage; unit m for x and y, km for chainage. ax : matplotlib.axes.Axes Axes object in which to add the markers. ndec : int Number of decimals used for marks. scale: float Indicates whether the axes are in m (1) or km (1000). """ step = 10**(-ndec) labelstr = " {:." + str(ndec) + "f}" km_rescaled = xykm[:, 2] / step mask = numpy.isclose(numpy.round(km_rescaled), km_rescaled) ax.plot( xykm[mask, 0] / scale, xykm[mask, 1] / scale, linestyle="None", marker="+", color="k", ) for i in numpy.nonzero(mask)[0]: ax.text( xykm[i, 0] / scale, xykm[i, 1] / scale, labelstr.format(xykm[i, 2]), fontsize="x-small", clip_on=True, )
def plot_delivered_vaccines_quantity(df_delivered: pd.DataFrame, ax: mp.axes.Axes) -> ResultValue: log = logging.getLogger('plot_delivered_vaccines_quantity') log.info(" >>") rv: ResultValue = ResultKo(Exception("Error")) try: line_label = "Dosi consegnate - somma" line_color = "#ff5733" df_delivered.sort_values(by="data_consegna", inplace=True) by_date = df_delivered.groupby(["data_consegna"]).sum() by_date.reset_index(level=0, inplace=True) by_date["cumulata"] = by_date["numero_dosi"].cumsum() x_del = by_date["data_consegna"] y_del = by_date["cumulata"] remove_tick_lines('x', ax) remove_tick_lines('y', ax) set_axes_common_properties(ax, no_grid=True) ax.xaxis.set_major_formatter(mdates.DateFormatter("%d/%m/%y")) ax.xaxis.set_minor_formatter(mdates.DateFormatter("%d/%m")) ax.xaxis.set_major_locator(mdates.DayLocator(interval=2)) ax.scatter(x_del, y_del, s=30, marker='.') line = ax.plot(x_del, y_del, 'b-', linewidth=2, color=line_color, label=line_label) ax.set_xticklabels(x_del, rotation=80) handles, labels = ax.get_legend_handles_labels() patch = mpatches.Patch(color=line_color, label=line_label) handles.append(patch) plt.legend(handles=handles, loc='upper left') rv = ResultOk(line) except Exception as ex: log.error("Exception caught - {ex}".format(ex=ex)) rv = ResultKo(ex) log.info(" <<") return rv
def plot_ic( ax: matplotlib.axes.Axes, ic: IonChromatogram, minutes: bool = False, **kwargs, ) -> List[Line2D]: """ Plots an Ion Chromatogram. :param ax: The axes to plot the IonChromatogram on. :param ic: Ion chromatogram m/z channels for plotting. :param minutes: Whether the x-axis should be plotted in minutes. Default :py:obj:`False` (plotted in seconds) :no-default minutes: :Other Parameters: :class:`matplotlib.lines.Line2D` properties. Used to specify properties like a line label (for auto legends), linewidth, antialiasing, marker face color. .. code-block:: python >>> plot_ic(im.get_ic_at_index(5), label='IC @ Index 5', linewidth=2) See :class:`matplotlib.lines.Line2D` for the list of possible keyword arguments. :return: A list of Line2D objects representing the plotted data. """ if not isinstance(ic, IonChromatogram): raise TypeError("'ic' must be an IonChromatogram") time_list = ic.time_list if minutes: time_list = [time / 60 for time in time_list] plot = ax.plot(time_list, ic.intensity_array, **kwargs) # Set axis ranges ax.set_xlim(min(time_list), max(time_list)) ax.set_ylim(bottom=0) return plot
def plot_ic(ax: matplotlib.axes.Axes, ic: IonChromatogram, minutes: bool = False, **kwargs) -> List[Line2D]: """ Plots an Ion Chromatogram :param ax: The axes to plot the IonChromatogram on :type ax: matplotlib.axes.Axes :param ic: Ion Chromatograms m/z channels for plotting :type ic: pyms.IonChromatogram.IonChromatogram :param minutes: Whether the x-axis should be plotted in minutes. Default False (plotted in seconds) :type minutes: bool, optional :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_ic(im.get_ic_at_index(5), label='IC @ Index 5', linewidth=2) See https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.lines.Line2D.html for the list of possible kwargs :return: A list of Line2D objects representing the plotted data. :rtype: list of :class:`matplotlib.lines.Line2D` """ if not isinstance(ic, IonChromatogram): raise TypeError("'ic' must be an IonChromatogram") time_list = ic.time_list if minutes: time_list = [time / 60 for time in time_list] plot = ax.plot(time_list, ic.intensity_array, **kwargs) # Set axis ranges ax.set_xlim(min(ic.time_list), max(ic.time_list)) ax.set_ylim(bottom=0) return plot