def shadowing(ax: plt.axes, sim: Simulation) -> int: center = np.array([0.5, 0.5, 0.5]) axis = np.array([1.0, 0.0, 0.0]) abundance = BasicField("ChemicalAbundances", 1) density = BasicField("Density", None) criticalDensity = 1e9 obstacle = TresholdField(density, criticalDensity, 0, 1) field = CombinedField([abundance, obstacle], [npRed, npBlue]) snap = sim.snapshots[-1] voronoiSlice(ax, sim, snap, field, axis) assert sim.params["densityFunction"] in ["shadowing1", "shadowing2"] if sim.params["densityFunction"] == "shadowing1": params = shadowing1Params else: params = shadowing2Params obstacleSize = params["size"] obstacleCenter = params["center"] # ax.plot((center[2], center[1]), (obstacleCenter[2], obstacleCenter[1] - obstacleSize)) x, y = center[2], center[1] ox, oy = obstacleCenter[2], obstacleCenter[1] delX = ox - x delY = oy - obstacleSize - y f = 2.0 ax.plot((x, x + delX * f), (y, y + delY * f), color="green") ax.plot((x, x + delX * f), (y, y - delY * f), color="green")
def annotate_points_with_images(ax: plt.axes, indices: Union[List[int], np.ndarray], plot_data: np.ndarray, image_data: np.ndarray, image_size: Tuple[int, int], xybox: Tuple[float, float] = (-40., 40.)) -> None: """ Annotates a plot of points with converted image data. :param ax: A matplotlib axes object :param indices: A list of indices to index image data and plot data. :param plot_data: A 2D projection of image data. :param image_data: Original image data, where each row corresponds to an array of image data. :param image_size: A tuple representing image size in pixels. :return: None """ for i in indices: ab = AnnotationBbox( OffsetImage( image_data[i, :].reshape(image_size[0], image_size[1]), zoom=.8, cmap='gray' ), tuple(plot_data[i, :]), xybox=xybox, xycoords='data', boxcoords="offset points", pad=0.3, arrowprops=dict(arrowstyle="->")) ax.add_artist(ab)
def get_matching_overlap(axis: plt.axes, collection_classes: List[NormalizedPeakCollection], long_mode: int, trans_mode: Union[int, None]) -> plt.axes: def get_normalized_cluster_pos( collection: NormalizedPeakCollection) -> float: _cluster = collection.get_labeled_clusters(long_mode=long_mode, trans_mode=trans_mode) _norm_pos = _cluster[0][ 0].get_norm_x # np.mean([peak.get_norm_x for peak in _cluster[0]]) return _norm_pos reference_norm_pos = get_normalized_cluster_pos( collection=collection_classes[0]) for i, norm_collection in enumerate(collection_classes): alpha = SECOND_ALPHA if i == len( collection_classes) - 1 else FIRST_ALPHA x_sample, y_measure = norm_collection.get_normalized_mode( long_mode=long_mode, trans_mode=trans_mode) x_diff = reference_norm_pos - get_normalized_cluster_pos( collection=norm_collection) axis.plot(x_sample + x_diff, y_measure, alpha=alpha) # Set axis axis = get_standard_axis(axis=axis) axis.set_xlabel('Relative distance between estimated q-modes' ) # 'Relative units' + r'$\times 2/\lambda$' return axis
def update_estimate_axes(axes: plt.axes, num_in_circle: int, current_iter: int) -> float: """ Updates the estimate axes with the new information prior to taking a snapshot. """ pi_est = estimate_pi(num_in_circle, current_iter) pi_formatted = f"{pi_est:.5f}" current_iter_formatted = f"Current iteration: {current_iter - 1}" num_in_circle_formatted = f"Points inside circle: {num_in_circle}" num_out_circle_formatted = f"Points outside circle: {current_iter - num_in_circle}" error = np.abs(np.pi - pi_est) error_formatted = f"Error: {error:.5f}" percent_error = error / np.pi * 100 percent_error_formatted = f"Relative error: {percent_error:.5f}%" axes.text(0, 0.7, pi_formatted, size=40, bbox={ "facecolor": "b", "alpha": 0.5 }) axes.text(0, 0.4, current_iter_formatted, size=15) axes.text(0, 0.25, num_in_circle_formatted, size=15) axes.text(0, 0.1, num_out_circle_formatted, size=15) axes.text(0, -0.05, error_formatted, size=15) axes.text(0, -0.2, percent_error_formatted, size=15) return pi_est
def _plot_pr_curve_iou_range( ax: plt.axes, coco_eval: CocoEvaluator, iou_type: Optional[str] = None, ) -> None: """ Plots the PR curve over varying iou thresholds averaging over [K] categories. """ x = np.arange(0.0, 1.01, 0.01) iou_thrs_idx = range(0, 10) iou_thrs = np.linspace(0.5, 0.95, np.round((0.95 - 0.5) / 0.05) + 1, endpoint=True) # get_cmap() - a function that maps each index in 0, 1, ..., n-1 to a distinct # RGB color; the keyword argument name must be a standard mpl colormap name. cmap = plt.cm.get_cmap("hsv", len(iou_thrs)) ax = _setup_pr_axes( ax, f"Precision-Recall Curve ({iou_type}) @ different IoU Thresholds") for i, c in zip(iou_thrs_idx, iou_thrs): arr = coco_eval.eval["precision"][_get_precision_recall_settings(i)] arr = np.average(arr, axis=1) ax.plot(x, arr, c=cmap(i), label=f"IOU={round(c, 2)}") ax.legend(loc="lower left")
def barh(ax: plt.axes, series: pd.Series, kwargs: Dict[str, Any]) -> None: """Add a horizontal bar chart.""" USE = ('color', 'c', 'alpha', 'label', 'width') param = get_selected_list(kwargs, USE) ax.barh(series.index.values, series.values, **param) annotate_barh(ax, series, kwargs) return None
def plot_agent(ax: plt.axes, position: Tuple, marker: str = "X", *args, **kwargs): ax.scatter(*position, marker=marker, *args, **kwargs)
def annotate3D(self, ax: plt.axes, x: np.array, y: np.array, z: np.array, labels: np.array) -> plt.axes: for i, name in enumerate(labels): if name in self.points_to_annotate: ax.text3D(x[i], y[i], z[i], name, size=12, zorder=1) return ax
def annotate(self, ax: plt.axes, x: np.array, y: np.array, labels: np.array) -> plt.axes: """ https://stackoverflow.com/questions/5147112/how-to-put-individual-tags-for-a-scatter-plot for more details Parameters ---------- ax x y labels Returns ------- """ for i, name in enumerate(labels): if name in self.points_to_annotate: ax.annotate(name, (x[i], y[i]), xytext=(-5, 10), textcoords='offset points', ha='center', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='white', alpha=0.2)) return ax
def bar(ax: plt.axes, series: pd.Series, kwargs: Dict[str, Any]) -> None: """Add a bar plot to a chart.""" recent = get_selected_item(kwargs, key='recent', default=0) USE = ('color', 'c', 'alpha', 'label', 'width') param = get_selected_list(kwargs, USE) ax.bar(series.index[-recent:], series.iloc[-recent:], **param) return None
def plot_lollipops( ax: plt.axes, positions: Sequence[float], heights: Union[float, Sequence[float]], **kwargs: Optional, ) -> None: """ Parameters ---------- ax positions label heights kwargs: Optional Keyword arguments passed to :py:func:`matplotlib.pyplot.scatter`. Useful options include label (used for figure legends), symbol, color, edgecolor, and zorder. Returns ------- """ if isinstance(heights, Sequence): if len(heights) != len(positions): raise ValueError( f"unequal number of lollipop heights ({len(heights)}) and positions ({len(positions)})" ) else: heights = [heights] * len(positions) for p, h in zip(positions, heights): ax.plot([p, p], [0.0, h], color="black", linestyle="-", linewidth=1, zorder=1) ax.scatter(x=positions, y=heights, **kwargs)
def plot_regression( ax: plt.axes, regression_data: pandas.DataFrame, ) -> plt.axes: """ Plot regression between dates and root-to-tip distances Data corresponds to `rtt.csv` output from TimeTree clock regression. :param ax: axes object to plot on :param regression_data: data frame with dates (x-axis, column 0) and root-to-tip distances (x-axis, column 0) :returns axes object """ x = regression_data.iloc[:, 0].values.reshape(-1, 1) # 2-d y = regression_data.iloc[:, 1].values.reshape(-1, 1) linear_regressor = LinearRegression() linear_regressor.fit(x, y) y_pred = linear_regressor.predict(y) ax.scatter(x, y) ax.plot(x, y_pred, color='r') return ax
def plot_line(ax: axes, ob: LineString, color: Optional[Text] = 'r', alpha: Optional[float] = 0.7, linewidth: Optional[float] = 3, solid_capstyle: Optional[Text] = 'round', zorder: Optional[float] = 2): """ Plot a LineString Parameters ---------- ax : axes Single axes object ob : LineString Sequence of points. color : str, optional Sets the line color, by default 'r' alpha : float, optional Defines the opacity of the line, by default 0.7 linewidth : float, optional Defines the line thickness, by default 3 solid_capstyle : str, optional Defines the style of the ends of the line, by default 'round' zorder : float, optional Determines the default drawing order for the axes, by default 2 """ x, y = ob.xy ax.plot(x, y, color=color, alpha=alpha, linewidth=linewidth, solid_capstyle=solid_capstyle, zorder=zorder)
def swarm_plot(panel: plt.axes, y_values: list, x_position: int or float, panel_width: int or float = None, panel_height: int or float = None, xmin: int or float = None, xmax: int or float = None, ymin: int or float = None, ymax: int or float = None, plot_width: int or float = None, minimum_distance: float = None, shift: float = None, size: float = None, color: list or str or tuple = None) -> plt.axes: if type(color) is list: if len(color) is 1: if type(color[0]) is list: color = [tuple(color[0])] * len(y_values) elif type(color[0]) is str: color = [color[0]] * len(y_values) elif type(color[0]) is tuple: color = [color[0]] * len(y_values) if len(color) is 3: color = [tuple(color)] * len(y_values) elif len(color) is len(y_values): pass else: sys.stderr.write( "Colors are not of correct format. Printing points in black. Param 'color' should be of " "type list<str>, list<list>, or list<tuple> and match length of y_values. Else, " "one value should be passed as the color for all points.") sys.exit(1) elif type(color) is str: color = [color] * len(y_values) elif type(color) is tuple: color = [color] * len(y_values) else: sys.stderr.write( "{} type for paramater 'color' is not valid. Please use a list<str> or list<rgb tuple> of colors, " "one for each Y value, or a single " "color in string or tuple format('black', '(1,1,1)').".format( str(type(color)))) sys.exit(1) y_values.sort() data = [[x_position, y_value] for y_value in y_values] for i, datum in enumerate(data): datum.append(color[i]) median = statistics.median([y[1] for y in data]) swarm_data = swarm_helper(data, shift, minimum_distance, size, xmin, xmax, ymin, ymax, panel_width, panel_height) panel.scatter([x[0] for x in swarm_data], [y[1] for y in swarm_data], c=[z[2] for z in swarm_data], s=float(math.sqrt(size)), linewidths=0) panel.plot([x_position - plot_width, x_position + plot_width], [median, median], linewidth=.7, color='red') return panel
def plot_cov(ax: plt.axes, mean: np.ndarray, cov_matrix: np.ndarray, color: str) -> None: # Helper function to visualize the distribution vals, vecs = np.linalg.eigh(cov_matrix) x, y = vecs[:, 0] theta = np.degrees(np.arctan2(y, x)) w, h = 2 * np.sqrt(vals) ax.add_artist(Ellipse(mean, w, h, theta, color=color, alpha=0.3))
def plot_trajectory(self, ax: plt.axes): # x-y plane projection for i in range(self.N): ax.scatter(np.array(self.position_history)[:, i, 0], np.array(self.position_history)[:, i, 1], s=1, label=self.names[i]) ax.legend()
def line(ax: plt.axes, series: pd.Series, kwargs: Dict[str, Any]) -> None: """Add a line plot to a chart.""" recent = get_selected_item(kwargs, key='recent', default=0) USE = ('color', 'c', 'alpha', 'label', 'linestyle', 'ls', 'linewidth', 'lw', 'marker') param = get_selected_list(kwargs, USE) ax.plot(series.index[-recent:], series.iloc[-recent:], **param) return None
def scatter(ax: plt.axes, series: pd.Series, kwargs: Dict[str, Any]): """Add a scatter plot to an axes.""" recent = get_selected_item(kwargs, key='recent', default=0) USE = ('c', 's', 'alpha', 'label') DEFAULTS = {'c': '#dd0000', 's': 10} params = add_defaults(get_selected_list(kwargs, USE), DEFAULTS) ax.scatter(series.index[-recent:], series.iloc[-recent:], **params) return None
def plot_position(self, axe: plt.axes, pos, symbol): """ Plot symbol in the game. "X" for black player and "O" for while player. """ row = self.size - 1 - pos // self.size column = pos % self.size axe.text(column, row, symbol, fontsize=120) plt.pause(1)
def plot_peak_collection(axis: plt.axes, data: Union[List[PeakData], PeakCollection], label: str = '') -> plt.axes: # Plot peaks x = [peak.get_x for peak in data] y = [peak.get_y for peak in data] axis.plot(x, y, 'x', label=label) return get_standard_axis(axis=axis)
def update_acc_time_axes(axes: plt.axes, estimates: [float]) -> None: """ Updates the accuracy over time axes with the new information prior to taking a snapshot. """ axes.hlines(y=np.pi, xmin=0, xmax=NUM_ITER, colors="b") axes.plot(range(0, CHECKPOINT_ITER * len(estimates), CHECKPOINT_ITER), estimates, color="orange")
def graph(x, y, ax: plt.axes): ax.plot(x, y, color='green') stop = len(y) for i in range(0, stop - 2): for j in range(i + 2, stop): for k in range(i + 1, j): if has_intersection([x[i], y[i]], [x[j], y[j]], [x[k], y[k]]): break else: ax.plot([x[i], x[j]], [y[i], y[j]])
def add_fragments_length_plot(ax: plt.axes, data: pd.DataFrame, color: str = plot_consts.FRAGMENT_LENGTH_COLOR, s: int = plot_consts.SMALL_SIZE, label: Optional[str] = None) -> None: ax.scatter(data[TIMESTAMP_COL], data[plot_consts.FRAGMENT_LENGTH_COL], color=color, s=s, label=label)
def calibrant_rings_image(self, ax: plt.axes) -> plt.axes: cal_img_masked = self.calibrant_rings() rings_img = ax.imshow(cal_img_masked, alpha=0.3, cmap="inferno", origin="lower") # add the beam position ax.plot(*self.beam_position(self.geometry), "rx") return rings_img
def get_standard_axis(axis: plt.axes) -> plt.axes: # Set axis axis.set_xlabel('Sampling Cavity Length [nm]') # Voltage [V] axis.set_ylabel('Transmission (log10(V))') axis.set_yscale('log') locs, labels = plt.yticks() yticks = [np.log10(value) for value in locs[0:-1]] plt.yticks(locs[0:-1], yticks) axis.set_ylim([10**(-4), 10**(1)]) # Custom y-lim axis.grid(True) return axis
def add_fragments_length_plot(ax: plt.axes, data: pd.DataFrame, color: str = plot_consts.FRAGMENT_LENGTH_COLOR, s: int = plot_consts.SMALL_SIZE, label: Optional[str] = None, to_connect: bool = False) -> None: ax.scatter(data[CT_SECONDS_COL], data[plot_consts.FRAGMENT_LENGTH_COL], color=color, s=s, label=label) if to_connect: ax.plot(data[CT_SECONDS_COL], data[plot_consts.FRAGMENT_LENGTH_COL])
def plot_maximum_distance(self, ax: plt.axes, *args, **kwargs): """Overlay the maximum distance between two points onto an existing axes, one with a world coordinate system included as the projection. All `*args` and `**kwargs` are passed onto `matplotlib.pyplot.scatter`. Arguments: ax {plt.axes} -- axes object to plot onto """ path = self.maximum_distance_positions ax.plot(path.ra, path.dec, *args, transform=ax.get_transform('world'), **kwargs)
def draw(self, ax: plt.axes, add_patch: bool = True): ''' * Represent a particle for animation. ''' rectangle = Rectangle((self._x[-1], self._y[-1]), self.length, self.width, edgecolor='r', fill=False) if add_patch: ax.add_patch(rectangle) return rectangle
def plot_eigenvalues(self, ax: plt.axes): # pragma: no cover """ Plot the eigenvalues of the :math:`R_{32}` matrix, so that the order of the state-space model can be determined. Since the :math:`R_{32}` matrix should have been calculated, this function can only be used after performing ``self.subspace_identification``. """ if self.R32_decomposition is None: raise Exception('Perform subspace identification first.') ax.semilogy(np.diagonal(self.R32_decomposition.eigenvalues), 'x') ax.set_title('Estimated observability matrix decomposition') ax.set_xlabel('Index') ax.set_ylabel('Eigenvalue') ax.grid()
def reg_plot(x_axis, y_axis, model_name: str, score: float, ax_i: plt.axes): """ Generates regplot using given vectors in given ax_i. Parameters --------- x_axis: 1D array like y_axis: 1D array like model_name: str score: float ax_i: plt.axes """ sns.set() sns.regplot(x_axis, y_axis, ax=ax_i) r, pvalue = scipy.stats.pearsonr(x_axis, y_axis) Mean_SE = np.mean((x_axis - y_axis)**2) ax_i.text( 70, 205, f"Pearson R: {r:.3f}\nP-value: {pvalue:.3e}\nMean SE: {Mean_SE:.2f}", va="top", ha="left", fontsize=10, ) ax_i.text(135, 75, f"Score (R^2): {score:.2f}", fontsize=13, ha="left") ax_i.set_title(f"{model_name}", fontsize=16) ax_i.set_xlabel("")