def plot_traps_legend(): plt.subplot(1, 3, 1) Legend.update_default_handler_map({str: TextHandlerB()}) plt.legend(handles=["S", "N", "R"], labels=["Security", "Normal", "Risky"], title="Dices", loc='center') plt.axis('off') plt.subplot(1, 3, 2) # handle1 = mpatches.FancyBboxPatch((0,0), 10, 10, boxstyle='Square, pad=0.5', facecolor='#f6f4f4', lw=0, label="False") # handle2 = mpatches.FancyBboxPatch((0,0), 10, 10, boxstyle='Circle, pad=0.5', facecolor='#f6f4f4', lw=0, label="False") handle1, = Line2D([0], [0], marker='s', color='w', label='False', markerfacecolor='lightgray', markersize=11), handle2, = Line2D([0], [0], marker='o', color='w', label='True', markerfacecolor='lightgray', markersize=11), plt.legend(handles=[handle1, handle2], loc='center', title='Circle') plt.axis('off') plt.subplot(1, 3, 3) handles = [] for i, label in enumerate(traps_label): if label: patch = mpatches.Patch(label=label, color=traps_color[i]) handles.append(patch) plt.legend(handles=handles, loc='center', title="Traps") plt.axis('off')
def scatter_football(x, y, ax=None, **kwargs): """ Scatter plot of football markers. Plots two scatter plots one for the hexagons and one for the pentagons of the football. Parameters ---------- x, y : array-like or scalar. Commonly, these parameters are 1D arrays. ax : matplotlib.axes.Axes, default None The axis to plot on. **kwargs : All other keyword arguments are passed on to matplotlib.axes.Axes.scatter. Returns ------- (paths, paths) : a tuple of matplotlib.collections.PathCollection """ linewidths = kwargs.pop('linewidths', 0.5) hexcolor = kwargs.pop('c', 'white') pentcolor = kwargs.pop('edgecolors', 'black') s = kwargs.pop('s', 500) sc_hex = ax.scatter(x, y, edgecolors=pentcolor, c=hexcolor, linewidths=linewidths, marker=football_hexagon_marker, s=s, **kwargs) if 'label' in kwargs.keys(): Legend.update_default_handler_map({sc_hex: HandlerFootball()}) del kwargs['label'] sc_pent = ax.scatter(x, y, edgecolors=pentcolor, c=pentcolor, linewidths=linewidths, marker=football_pentagon_marker, s=s, **kwargs) return sc_hex, sc_pent
def plot_list(L_value_list, optpdf, color, alpha): class TextHandlerB(HandlerBase): def create_artists(self, legend, text, xdescent, ydescent, width, height, fontsize, trans): tx = Text(width / 2., height / 2, text, fontsize=fontsize, ha="center", va="center", fontweight="normal") return [tx] Legend.update_default_handler_map({str: TextHandlerB()}) f = plt.figure(figsize=(8, 4)) (mu, sigma) = norm.fit(L_value_list) pvalue = norm.pdf(48, mu, sigma) pvalue = "%.2e" % pvalue ax=sns.distplot(pd.Series(L_value_list),bins=np.arange(25,36,1),fit=norm,kde=False,\ kde_kws={"label":"Smooth",'linewidth':1.5,"linestyle":"--","color":"K"},\ fit_kws={'label': 'Normal','linewidth':1.5, "color": "r"},hist_kws={'linewidth':0.05,"color": color,"edgecolor":"black","alpha":alpha,"align":"mid","rwidth":1},label=str(pvalue))#,ax=ax) plt.axvline(48, color='r') legend_i = ax.get_legend_handles_labels() smooth_normal_handles = legend_i[0][:1] smooth_normal_handles.append("Pvalue ") plt.xticks(np.arange(min(L_value_list) - 2, 55, 1)) #max(L_value_list)+3,1)) plt.legend(smooth_normal_handles, legend_i[1], loc='upper right', framealpha=0) plt.ylabel("Probability", fontsize=10, fontweight='semibold') plt.xlabel("Bottleneck Size,n", fontsize=10, fontweight='semibold') plt.title("The distribution of n", fontsize=12, fontweight='bold') plt.tight_layout() plt.savefig(optpdf, dpi=200)
def visualize_genome(genome: Genome, show_learning_rules: bool = True, with_legend: bool = True): def get_color(node: NodeGene): if isinstance(node, InputNodeGene): return GREEN elif isinstance(node, (HiddenNodeGene, OutputNodeGene)): if node.is_inhibitory: if node.bias: return PINK else: return RED else: if node.bias: return CYAN else: return BLUE def legend_circle(color: str): return Line2D([0], [0], color=color, marker='o', linewidth=0) g, nodes, edges = genome_to_graph(genome) pos = get_node_coordinates(genome) labels = { key: f"{node.learning_rule.value if isinstance(node, NeuralNodeGene) else key}{'↩' if (key, key) in edges else ''}" for key, node in genome.nodes.items()} if show_learning_rules \ else {node: f"{node}{'↩' if (node, node) in edges else ''}" for node in nodes} node_color = [get_color(genome.nodes[node]) for node in nodes] edgecolors = [ 'k' if isinstance(genome.nodes[node], OutputNodeGene) else get_color( genome.nodes[node]) for node in nodes ] nx.draw_networkx_nodes(g, pos=pos, nodes=nodes, node_color=node_color, edgecolors=edgecolors, node_size=400) nx.draw_networkx_labels(g, pos=pos, labels=labels) nx.draw_networkx_edges(g, pos=pos, connectionstyle="arc3, rad=0.05") # nx.draw_networkx(g, pos=pos, with_labels=True, labels=labels, nodes=nodes, node_color=node_color, node_size=400, # font_size=10, connectionstyle="arc3, rad=0.05") Legend.update_default_handler_map({Text: CustomTextHandler()}) legend_dict = { legend_circle(GREEN): 'input node', Line2D([0], [0], color='w', markeredgecolor='k', marker='o', linewidth=0): 'output node', legend_circle(BLUE): 'excitatory, without bias', legend_circle(RED): 'inhibitory, without bias', legend_circle(CYAN): 'excitatory, with bias', legend_circle(PINK): 'inhibitory, with bias', Text(text='AH'): 'asymmetric hebbian', Text(text='AA'): 'asymmetric anti-hebbian', Text(text='SH'): 'symmetric hebbian', Text(text='SA'): 'symmetric anti-hebbian' } if with_legend: plt.figlegend(handles=legend_dict.keys(), labels=legend_dict.values(), loc='upper right') plt.box(False) plt.show()
"ks.mplstyle")) # this should be the path to the directory of the current file "fc_plotting.py", # and ks.mplstyle is supposed to be in the same directory # A legend handler to add simple left-aligned text strings to the legend, e.g. (sub)titles class StringLegendHandler(HandlerBase): def create_artists(self, legend, text, xdescent, ydescent, width, height, fontsize, trans): txt = Text(-1, 1, text, fontsize='x-large', ha="left", va="baseline") txt.set_transform(trans) return [txt] Legend.update_default_handler_map({str: StringLegendHandler()}) # Some constants to use in plotting ALPHA_PARANOME_HISTOGRAM = 0.75 ALPHA_ANCHOR_HISTOGRAM = 0.75 ALPHA_DIVERGENCE_RECT = 0.3 ALPHA_DIVERGENCE_LINE = 0.6 COLOR_PARANOME_HISTOGRAM = to_rgba("0.79", ALPHA_PARANOME_HISTOGRAM) COLOR_ANCHOR_HISTOGRAM = to_rgba("0.64", ALPHA_ANCHOR_HISTOGRAM) COLOR_PARANOME_KDE = "0.6" COLOR_ANCHOR_KDE = "0.4" SIZE_CIRCLE_LABEL_WHITE = 220 LINEWIDTH_CIRCLE_LABEL_BORDER = 1
self._patch_func = patch_func def create_artists (self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): x0, y0 = xdescent, ydescent width, height = width, height linewidth = orig_handle.get_linewidth () [0] if len (orig_handle.get_linewidth ()) != 0 else None patch = matplotlib.patches.Rectangle([x0, y0], width, height, hatch=orig_handle.get_hatch (), lw=linewidth, transform=trans) cmap = orig_handle.get_cmap () patch.set_facecolor (orig_handle.get_cmap () (0.5)) patch.set_edgecolor (orig_handle.get_edgecolor () [0]) return [patch] Legend.update_default_handler_map({matplotlib.collections.PolyCollection: PolyCollectionHandler()}) class KippenhahnPlot(object): """This object takes a matplotlib axis and attaches a Kippenhahn plot to it associated with the given CNVFile""" def __init__(self, axis, cnv_file, useModels = False): super(KippenhahnPlot, self).__init__() self.axis = axis self.cnv_file = cnv_file self.times = (u.Quantity ([model ['timesec'] for model in self.cnv_file], 's').to ('year')).value if (not useModels): self.x = self.times else: self.x = list (range (len (self.times)))
legline1.set_transform(trans) legline2.set_transform(trans) return [legline1, legline2] class HandlerPatch2(HandlerBase): """ Handler for Patch instances. """ def __init__(self, **kw): HandlerBase.__init__(self, **kw) def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): p1 = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) p2 = Rectangle(xy=(-xdescent, -ydescent), width=width, height=height) self.update_prop(p1, orig_handle, legend) self.update_prop(p2, orig_handle, legend) p2.set_facecolor('none') p1.set_transform(trans) p2.set_transform(trans) return [p1,p2] Legend.update_default_handler_map({ErrorLine2D: HandlerErrorLine2D()}) Legend.update_default_handler_map({Patch: HandlerPatch2()})
def lines(xstart, ystart, xend, yend, color=None, n_segments=100, comet=False, transparent=False, alpha_start=0.01, alpha_end=1, cmap=None, ax=None, vertical=False, reverse_cmap=False, **kwargs): """ Plots lines using matplotlib.collections.LineCollection. This is a fast way to plot multiple lines without loops. Also enables lines that increase in width or opacity by splitting the line into n_segments of increasing width or opacity as the line progresses. Parameters ---------- xstart, ystart, xend, yend: array-like or scalar. Commonly, these parameters are 1D arrays. These should be the start and end coordinates of the lines. color : A matplotlib color or sequence of colors, defaults to None. Defaults to None. In that case the marker color is determined by the value rcParams['lines.color'] n_segments : int, default 100 If comet=True or transparent=True this is used to split the line into n_segments of increasing width/opacity. comet : bool default False Whether to plot the lines increasing in width. transparent : bool, default False Whether to plot the lines increasing in opacity. linewidth or lw : array-like or scalar, default 5. Multiple linewidths not supported for the comet or transparent lines. alpha_start: float, default 0.01 The starting alpha value for transparent lines, between 0 (transparent) and 1 (opaque). If transparent = True the line will be drawn to linearly increase in opacity between alpha_start and alpha_end. alpha_end : float, default 1 The ending alpha value for transparent lines, between 0 (transparent) and 1 (opaque). If transparent = True the line will be drawn to linearly increase in opacity between alpha_start and alpha_end. cmap : str, default None A matplotlib cmap (colormap) name vertical : bool, default False If the orientation is vertical (True), then the code switches the x and y coordinates. reverse_cmap : bool, default False Whether to reverse the cmap colors. If the pitch is horizontal and the y-axis is inverted then set this to True. ax : matplotlib.axes.Axes, default None The axis to plot on. **kwargs : All other keyword arguments are passed on to matplotlib.collections.LineCollection. Returns ------- LineCollection : matplotlib.collections.LineCollection Examples -------- >>> from mplsoccer import Pitch >>> pitch = Pitch() >>> fig, ax = pitch.draw() >>> pitch.lines(20, 20, 45, 80, comet=True, transparent=True, ax=ax) >>> from mplsoccer.linecollection import lines >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> lines([0.1, 0.4], [0.1, 0.5], [0.9, 0.4], [0.8, 0.8], ax=ax) """ validate_ax(ax) if not isinstance(comet, bool): raise TypeError( "Invalid argument: comet should be bool (True or False).") if not isinstance(transparent, bool): raise TypeError( "Invalid argument: transparent should be bool (True or False).") if alpha_start < 0 or alpha_start > 1: raise TypeError("alpha_start values should be within 0-1 range") if alpha_end < 0 or alpha_end > 1: raise TypeError("alpha_end values should be within 0-1 range") if alpha_start > alpha_end: msg = "Alpha start > alpha end. The line will increase in transparency nearer to the end" warnings.warn(msg) if 'colors' in kwargs.keys(): warnings.warn( "lines method takes 'color' as an argument, 'colors' in ignored") if color is not None and cmap is not None: raise ValueError("Only use one of color or cmap arguments not both.") if 'lw' in kwargs.keys() and 'linewidth' in kwargs.keys(): raise TypeError( "lines got multiple values for 'linewidth' argument (linewidth and lw)." ) # set linewidth if 'lw' in kwargs.keys(): lw = kwargs.pop('lw', 5) elif 'linewidth' in kwargs.keys(): lw = kwargs.pop('linewidth', 5) else: lw = 5 # to arrays xstart = np.ravel(xstart) ystart = np.ravel(ystart) xend = np.ravel(xend) yend = np.ravel(yend) lw = np.ravel(lw) if (comet or transparent) and (lw.size > 1): msg = "Multiple linewidths with a comet or transparent line is not implemented." raise NotImplementedError(msg) # set color if color is None and cmap is None: color = rcParams['lines.color'] if (comet or transparent) and (cmap is None) and ( to_rgba_array(color).shape[0] > 1): msg = "Multiple colors with a comet or transparent line is not implemented." raise NotImplementedError(msg) if xstart.size != ystart.size: raise ValueError("xstart and ystart must be the same size") if xstart.size != xend.size: raise ValueError("xstart and xend must be the same size") if ystart.size != yend.size: raise ValueError("ystart and yend must be the same size") if (lw.size > 1) and (lw.size != xstart.size): raise ValueError("lw and xstart must be the same size") if lw.size == 1: lw = lw[0] if vertical: ystart, xstart = xstart, ystart yend, xend = xend, yend # create linewidth if comet: lw = np.linspace(1, lw, n_segments) handler_first_lw = False else: handler_first_lw = True if (transparent is False) and (comet is False) and (cmap is None): multi_segment = False else: multi_segment = True if transparent: cmap = create_transparent_cmap(color, cmap, n_segments, alpha_start, alpha_end) if isinstance(cmap, str): cmap = get_cmap(cmap) if cmap is not None: handler_cmap = True line_collection = _lines_cmap(xstart, ystart, xend, yend, lw=lw, cmap=cmap, ax=ax, n_segments=n_segments, multi_segment=multi_segment, reverse_cmap=reverse_cmap, **kwargs) else: handler_cmap = False line_collection = _lines_no_cmap(xstart, ystart, xend, yend, lw=lw, color=color, ax=ax, n_segments=n_segments, multi_segment=multi_segment, **kwargs) line_collection_handler = HandlerLines(numpoints=n_segments, invert_y=reverse_cmap, first_lw=handler_first_lw, use_cmap=handler_cmap) Legend.update_default_handler_map( {line_collection: line_collection_handler}) return line_collection
xdescent, ydescent, width, height, fontsize, trans): center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent p = patches.FancyArrow( xdescent, 0.5 * height, width, 0., length_includes_head=True, head_width=0.75 * height, facecolor=orig_handle.get_facecolor(), edgecolor=orig_handle.get_edgecolor(), ) p.set_transform(trans) return [p] Legend.update_default_handler_map({ patches.Circle: HandlerCircle(), patches.FancyArrow: HandlerArrow() }) def set_ax_params(ax, facecolor="lightgrey"): ax.set_aspect(1) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.tick_params("both", bottom="off", left="off") ax.set_facecolor(facecolor) R = re.compile(r"^(\d+)\(([\d\.]+)\) : (\d+)\|(\d+)\|(\d+)$", re.MULTILINE) Stat = namedtuple("Stat", ["episodes", "time", "win_rate", "lose_rate", "draw_rate"])
def arrows(xstart, ystart, xend, yend, *args, ax=None, vertical=False, **kwargs): """ Utility wrapper around matplotlib.axes.Axes.quiver. Quiver uses locations and direction vectors usually. Here these are instead calculated automatically from the start and endpoints of the arrow. The function also automatically flips the x and y coordinates if the pitch is vertical. Plot a 2D field of arrows. See: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.quiver.html Parameters ---------- xstart, ystart, xend, yend: array-like or scalar. Commonly, these parameters are 1D arrays. These should be the start and end coordinates of the lines. C: 1D or 2D array-like, optional Numeric data that defines the arrow colors by colormapping via norm and cmap. This does not support explicit colors. If you want to set colors directly, use color instead. The size of C must match the number of arrow locations. ax : matplotlib.axes.Axes, default None The axis to plot on. vertical : bool, default False If the orientation is vertical (True), then the code switches the x and y coordinates. width : float, default 4 Arrow shaft width in points. headwidth : float, default 3 Head width as a multiple of the arrow shaft width. headlength : float, default 5 Head length as a multiple of the arrow shaft width. headaxislength : float, default: 4.5 Head length at the shaft intersection. If this is equal to the headlength then the arrow will be a triangular shape. If greater than the headlength then the arrow will be wedge shaped. If less than the headlength the arrow will be swept back. color : color or color sequence, optional Explicit color(s) for the arrows. If C has been set, color has no effect. linewidth or linewidths or lw : float or sequence of floats Edgewidth of arrow. edgecolor or ec or edgecolors : color or sequence of colors or 'face' alpha : float or None Transparency of arrows. **kwargs : All other keyword arguments are passed on to matplotlib.axes.Axes.quiver. Returns ------- PolyCollection : matplotlib.quiver.Quiver Examples -------- >>> from mplsoccer import Pitch >>> pitch = Pitch() >>> fig, ax = pitch.draw() >>> pitch.arrows(20, 20, 45, 80, ax=ax) >>> from mplsoccer.quiver import arrows >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> arrows([0.1, 0.4], [0.1, 0.5], [0.9, 0.4], [0.8, 0.8], ax=ax) >>> ax.set_xlim(0, 1) >>> ax.set_ylim(0, 1) """ validate_ax(ax) # set so plots in data units units = kwargs.pop('units', 'inches') scale_units = kwargs.pop('scale_units', 'xy') angles = kwargs.pop('angles', 'xy') scale = kwargs.pop('scale', 1) width = kwargs.pop('width', 4) # fixed a bug here. I changed the units to inches and divided by 72 # so the width is in points, i.e. 1/72th of an inch width = width / 72. xstart = np.ravel(xstart) ystart = np.ravel(ystart) xend = np.ravel(xend) yend = np.ravel(yend) if xstart.size != ystart.size: raise ValueError("xstart and ystart must be the same size") if xstart.size != xend.size: raise ValueError("xstart and xend must be the same size") if ystart.size != yend.size: raise ValueError("ystart and yend must be the same size") # vectors for direction u = xend - xstart v = yend - ystart if vertical: ystart, xstart = xstart, ystart v, u = u, v q = ax.quiver(xstart, ystart, u, v, *args, units=units, scale_units=scale_units, angles=angles, scale=scale, width=width, **kwargs) quiver_handler = HandlerQuiver() Legend.update_default_handler_map({q: quiver_handler}) return q