def __init__(self): # Vertex is represented by a tuple (traj_idx, ob_idx) # Use node attribute to access data self.graph = nx.DiGraph() self.trajs = {} self.cm = matplotlib.cm.get_cmap('tab10') self.arrow_styles = [ ArrowStyle('->', head_length=2.0, head_width=2.0), # ArrowStyle('-|>', head_length=2.0, head_width=2.0), ArrowStyle('-[', widthB=3.0, lengthB=2.0) ] self.line_widths = [1.0, 2.0] self.line_styles = ['-', '-.']
def draw(self, ax=None): self.ax = ax or self.ax or plt.gca() x1, y1 = np.cos(self.angle) * self.circ_stretch * self.r, np.sin( self.angle) * self.circ_stretch * self.r theta1 = self.angle + np.pi - self.shrink theta2 = self.angle - np.pi + self.shrink rs = np.linspace(theta2, theta1) xs = np.cos(rs) * self.circ_rad * self.r + x1 ys = np.sin(rs) * self.circ_rad * self.r + y1 path = Path(np.stack((xs, ys)).T) self.arrow = FancyArrowPatch(path=path, arrowstyle=ArrowStyle( self.arrowstyle, head_length=self.head_length, head_width=self.head_width), linewidth=self.edgewidth, color=self.edgecolor) self.ax.add_patch(self.arrow) if self.label is not None: self.ax.text(x1 * self.circ_stretch, y1 * self.circ_stretch, self.label, horizontalalignment='center', verticalalignment='center', bbox=dict(facecolor=self.label_facecolor, edgecolor=self.label_edgecolor, alpha=0), color=self.label_color, fontname=self.fontname, fontsize=self.fontsize)
def _get_vis_style(self, u, v): arrow_styles = self.arrow_styles line_widths = self.line_widths line_styles = self.line_styles cm = self.cm if u[0] == v[0]: return { 'color': self.get_traj_vis_color(u[0]), 'arrowstyle': arrow_styles[(u[0] // cm.N) % len(arrow_styles)], 'linewidth': line_widths[(u[0] // (cm.N * len(arrow_styles))) % len(line_widths)], 'linestyle': line_styles[(u[0] // (cm.N * len(arrow_styles) * len(line_widths))) % len(line_styles)] } else: return { 'color': (0.8, 0.8, 0.8), 'linestyle': ':', 'linewidth': 0.5, 'arrowstyle': ArrowStyle('-|>', head_length=1.0, head_width=1.0) }
def draw(self, axes, feature, bbox, loc, style_param): from matplotlib.patches import FancyArrowPatch, ArrowStyle from matplotlib.path import Path x_center = bbox.x0 + bbox.width / 2 y_center = bbox.y0 + bbox.height / 2 path = Path(vertices=[ (bbox.x0, y_center), (bbox.x0, y_center - bbox.height / 2 * self._head_height), (bbox.x1, y_center - bbox.height / 2 * self._head_height), ], codes=[Path.MOVETO, Path.CURVE3, Path.CURVE3]) style = ArrowStyle.CurveFilledB(head_width=self._head_width, head_length=self._head_length) arrow = FancyArrowPatch(path=path, arrowstyle=style, linewidth=self._line_width, color="black") axes.add_patch(arrow) if "note" in feature.qual: axes.text(x_center, y_center + bbox.height / 4, feature.qual["note"], color="black", ha="center", va="center", size=9)
class Curve: """Part of a complete reaction curve. As an example, a reaction between a substrate and a product usually consists of two curves. The first curve has no arrowhead (i.e. has arrowstyle '-') and the second has an arrowhead pointing to the product.""" role_arrowstyles = [ "-", # SUBSTRATE "-|>", # PRODUCT "-", # SIDESUBSTRATE "-|>", # SIDEPRODUCT "-|>", # MODIFIER "-|>", # ACTIVATOR ArrowStyle("|-|", widthA=0, angleA=None, widthB=1.0, angleB=None) # INHIBITOR ] def __init__(self, h_curve): self.curveCPs = sbnw.getCurveCPs(h_curve) self.start_point = self.curveCPs.start self.end_point = self.curveCPs.end self.control_point_1 = self.curveCPs.control_point_1 self.control_point_2 = self.curveCPs.control_point_2 self.role = sbnw.curve_getRole(h_curve) self.role_name = Role(self.role).name self.curveArrowStyle = Curve.role_arrowstyles[self.role] self.edge_color = "#0000ff" self.fill_color = "#0000ff" self.curve_width = 3 self.species = None self.endHead = None
def draw_network(G, pos, ax, sg=None): for n in G: c = Circle(pos[n], radius=0.09, alpha=0.1, ) ax.add_patch(c) G.node[n]['patch'] = c x, y = pos[n] seen = {} for (u, v, d) in G.edges(data=True): # print('-->',u,v,d) n1 = G.node[u]['patch'] n2 = G.node[v]['patch'] rad = 0.3 if (u, v) in seen: rad = seen.get((u, v)) rad = (rad + np.sign(rad) * 0.1) * -1 alpha = d['weight'] / 10 color = 'k' ast = ArrowStyle("-|>, head_length=" + str( (1 + alpha) * (1 + alpha) * (1 + alpha) * (1 + alpha) * (1 + alpha) / 14) + ", head_width=0.2") e = FancyArrowPatch(n1.center, n2.center, patchA=n1, patchB=n2, arrowstyle=ast, connectionstyle='arc3,rad=%s' % rad, mutation_scale=17.0, lw=2, alpha=alpha, color=color, linewidth=alpha * alpha + 0.3, antialiased=True) seen[(u, v)] = rad ax.add_patch(e) return e
def plot_world(self, world): """ :param world: class World, the world we want to plot :return: fig, ax: a figure and an axes (matplotlib), these contain the plot of the world """ # Declare figure and axis fig, ax = plt.subplots(1, 1) fig.set_size_inches(12, 12) # Draw graph (see draw_networkx for all possible parameters) nx.draw_networkx(world.graph, pos=nx.circular_layout(world.graph), ax=ax, arrowstyle=ArrowStyle.CurveFilledB(head_length=0.5, head_width=0.3), arrowsize=max(-0.04 * world.graph.order() + 10, 1), with_labels=True, node_size=500, node_color=[ self.determine_color_node(agent) for agent in world.agents.values() ], alpha=0.8, linewidths=0.0, width=0.2) # Add a legend to the plot ax.legend(handles=self.legend) return fig, ax
def draw_tsp_route(c, csr, route, start): """巡回ルートの描画 :param c: ノード座標 :type c: np.ndarray (nodes_num, 2) :param csr: 隣接行列 :type csr: np.ndarray (nodes_num, nodes_num) :param route: 巡回ルート :type route: np.ndarray (nodes_num, ) :param start: スタートかつゴールのノード番号(c, csrの行インデックス) :type start: int :return: None """ # draw nodes plt.scatter(c[:, 0], c[:, 1], marker='o', s=200) for i in range(c.shape[0]): plt.text(c[i, 0]+0.1, c[i, 1]+0.1, i, size=20) # start node -> red plt.scatter(c[start, 0], c[start, 1], marker='o', s=200, color='red') # draw route route = np.append(route, 0) for i in range(len(route)-1): plt.annotate('', xy=(c[route[i], 0],c[route[i], 1]), xytext=(c[route[i+1], 0], c[route[i+1], 1]), arrowprops=dict(arrowstyle=ArrowStyle('<|-', head_length=1, head_width=0.5))) plt.text((c[route[i], 0]+c[route[i+1], 0])/2, (c[route[i], 1]+c[route[i+1], 1])/2, csr[ route[i], route[i+1]], color='k', size=15) plt.grid(which='major',color='gray',linestyle='-') plt.show()
def _next_frame(self, t): """ Creates plot for the next frame in the animation. :param t: integer, the time step in the animation :return: matplotlib.plot, a plot which is the next frame in the animation """ print(t, end='\r') # Clear the axis from the previous plot self.animation_axis.clear() # Fill the axis with the new plot world = self.simulation.simulation_data[t] nx.draw_networkx(world.graph, pos=nx.circular_layout(world.graph), ax=self.animation_axis, arrowstyle=ArrowStyle.CurveFilledB(head_length=0.5, head_width=0.3), arrowsize=max(-0.04 * world.graph.order() + 10, 1), with_labels=True, node_size=500, node_color=[ self.determine_color_node(agent) for agent in world.agents.values() ], alpha=0.8, linewidths=0.0, width=0.2) # Add legend and title self.animation_axis.legend(handles=self.legend) self.animation_axis.set_title('Frame ' + str(t)) # Return the plot return self.animation_axis.plot()
def __init__(self, layers, nodes, link_p): # Initialize parameters # Network parameters self.layers = layers self.nodes = nodes self.link_p = link_p self.link_w_base = 0.25 self.link_w_dev = 0.05 self.node_q_init = 2 # Drawing parameters self.node_size_min = 0.4 self.node_font_sizes = int(20 * self.node_size_min) self.mln_node_size = 0.15 self.node_size_scaling = 3000 self.link_size_scaling = 10 self.mln_node_sizes = self.layers * self.nodes * [ self.mln_node_size * self.node_size_scaling ] self.dynamic_node_range = range(self.layers * self.nodes, (self.layers + 1) * self.nodes) self.colors = ['#003071', 'white', 'grey'] self.arrow = ArrowStyle('simple', head_length=25, head_width=20, tail_width=.75) self.layer_y_dist = 15 self.layer_scale = 3 self.dynamic_node_scale = 3 self.dynamic_node_lim_x_offset = 1 self.dynamic_node_lim_y_offset = 3 self.txt_font_size = 15 self.mln_idx = self.nodes * self.layers # Simulation parameters self.iterations = 1000 self.link_mod_base = 1 self.link_mod_dev = 0.15 self.node_q_min = 0.01 self.node_q_max = 3 self.link_w_min = 0.01 self.link_w_max = 1 # Optional node dynamics self.funcs = [] func1 = lambda x: np.tanh(x) func2 = lambda x: -1 * np.tanh(x) for n in range(self.nodes): self.funcs.append(func1) if np.random.uniform( ) > 0.5 else self.funcs.append(func2) # Set up the figure pylab.ion() self.fig = plt.figure(0, figsize=(16, 8)) self.fig.canvas.set_window_title('Co-evolving Multilayer Network') self.ax_mln = plt.subplot2grid((5, 2), (0, 0), colspan=1, rowspan=5) self.ax_nodes = plt.subplot2grid((5, 2), (0, 1), colspan=1, rowspan=2) self.ax_3 = plt.subplot2grid((5, 2), (2, 1), colspan=1, rowspan=3) self.fig.tight_layout(pad=3, h_pad=1.25, w_pad=1.25)
def mplu_arrow(ax, x0, y0, x1, y1, **kwargs): _color = kwargs.get('color', 'black') _scale = kwargs.get('scale', 25) arrow = FancyArrowPatch((x0, y0), (x1, y1), arrowstyle=ArrowStyle('Simple', head_width=1, head_length=1), mutation_scale=_scale) arrow.set_color(_color) ax.add_artist(arrow)
def plot_1D(self, ticket, col, title, xtitle, ytitle, xum="", xrange=None, use_default_factor=True): if use_default_factor: factor = SRWPlot.get_factor(col) else: factor = 1.0 if isinstance(ticket['histogram'].shape, list): histogram = ticket['histogram'][0] else: histogram = ticket['histogram'] bins = ticket['bins'] if not xrange is None: good = numpy.where((bins >= xrange[0]) & (bins <= xrange[1])) bins = bins[good] histogram = histogram[good] bins *= factor self.plot_canvas.addCurve(bins, histogram, title, symbol='', color='blue', replace=True) #'+', '^', ',' if not xtitle is None: self.plot_canvas.setGraphXLabel(xtitle) if not ytitle is None: self.plot_canvas.setGraphYLabel(ytitle) if not title is None: self.plot_canvas.setGraphTitle(title) self.plot_canvas.setDrawModeEnabled(True, 'rectangle') self.plot_canvas.setZoomModeEnabled(True) if ticket['fwhm'] == None: ticket['fwhm'] = 0.0 n_patches = len(self.plot_canvas._backend.ax.patches) if (n_patches > 0): self.plot_canvas._backend.ax.patches.remove(self.plot_canvas._backend.ax.patches[n_patches-1]) if not ticket['fwhm'] == 0.0: x_fwhm_i, x_fwhm_f = ticket['fwhm_coordinates'] x_fwhm_i, x_fwhm_f = x_fwhm_i*factor, x_fwhm_f*factor y_fwhm = max(histogram)*0.5 self.plot_canvas._backend.ax.add_patch(FancyArrowPatch([x_fwhm_i, y_fwhm], [x_fwhm_f, y_fwhm], arrowstyle=ArrowStyle.CurveAB(head_width=2, head_length=4), color='b', linewidth=1.5)) if min(histogram) < 0: self.plot_canvas.setGraphYLimits(min(histogram), max(histogram)) else: self.plot_canvas.setGraphYLimits(0, max(histogram)) self.plot_canvas.replot() self.info_box.total.setText("{:.2e}".format(decimal.Decimal(ticket['total']))) self.info_box.fwhm_h.setText("{:5.4f}".format(ticket['fwhm']*factor)) self.info_box.label_h.setText("FWHM " + xum)
def draw(self) -> None: style = ArrowStyle("Simple, head_length=0.1, head_width=0.1, tail_width=0.02") arrow = FancyArrowPatch(self.point[:2], (self.point + self.vector)[:2], arrowstyle=style, edgecolor=self.color, facecolor=self.color, zorder=self.zorder, mutation_scale=100) if self.draw_point: self._point_artist = self.plotter.add(self.point, edgecolor=self.color) self._mpl_vector = self.plotter.axes.add_patch(arrow)
def draw_arrows2(self, arrows): for data in arrows: a = data['start'][:2] b = data['end'][:2] color = data.get('color', (0.0, 0.0, 0.0)) style = ArrowStyle("Simple, head_length=.1, head_width=.1, tail_width=.02") arrow = FancyArrowPatch(a, b, arrowstyle=style, edgecolor=color, facecolor=color, zorder=2000, mutation_scale=100) self.axes.add_patch(arrow)
def add_point(ax, pos, x_range, y_range, name, color): x, y = pos if math_ops.is_in_range(x, x_range) and math_ops.is_in_range(y, y_range): ax.scatter(x, y, marker='.', facecolors='none', edgecolor=color, zorder=1) ax.text(math_ops.scale_in_range(x, x_range, 0.01), math_ops.scale_in_range(y, y_range, 0.01), name, color=color, size=8, zorder=2) else: act_x, act_y = (x, x), (y, y) ha, va = 'center', 'center' if not math_ops.is_in_range(y, y_range): if y < y_range[0]: act_y = (math_ops.scale_in_range(y_range[0], y_range, 0.05), math_ops.scale_in_range(y_range[0], y_range, 0.01)) va = 'bottom' else: act_y = (math_ops.scale_in_range(y_range[1], y_range, -0.05), math_ops.scale_in_range(y_range[1], y_range, -0.01)) va = 'top' if not math_ops.is_in_range(x, x_range): if x < x_range[0]: act_x = (math_ops.scale_in_range(x_range[0], x_range, 0.05), math_ops.scale_in_range(x_range[0], x_range, 0.01)) ha = 'left' else: act_x = (math_ops.scale_in_range(x_range[1], x_range, -0.05), math_ops.scale_in_range(x_range[1], x_range, -0.01)) ha = 'right' arrow = FancyArrowPatch((act_x[0], act_y[0]), (act_x[1], act_y[1]), mutation_scale=5., arrowstyle=ArrowStyle('-|>'), fc=color, ec=color) ax.add_patch(arrow) ax.text(act_x[0], act_y[0], name, ha=ha, va=va, color=color, size=8, zorder=2)
def isochrones_subfig( fig_: Figure, x_: np.ndarray, y_: np.ndarray, color_: str = gray_ ) -> Tuple[Axes, Tuple[float, float]]: r"""Generate an isochrones subfig for embedding.""" # Top left isochrones 0 size_zoom_0: Tuple[float, float] = (0.65, 0.55) posn_0: Tuple[float, float] = (0.0, 0.75) axes_0 = fig_.add_axes([*posn_0, *size_zoom_0]) plt.axis("off") n_isochrones = 6 for i_, sf_ in enumerate(np.linspace(0.5, 1.2, n_isochrones)): plt.plot( *(x_, sf_ * y_), "-", color=self.gray_color(i_, n_gray), lw=2.5, ) plt.xlim(0, 1) plt.ylim(0, 1) sf1_ = 1.3 sf2_ = 1.3 arrow_xy_: np.ndarray = np.array([0.2, 0.8]) arrow_dxy_: np.ndarray = np.array([-0.025, 0.15]) motion_xy_: Tuple[float, float] = (0.1, 0.8) motion_angle_ = 23 my_arrow_style = ArrowStyle.Simple( head_length=1 * sf1_, head_width=1 * sf1_, tail_width=0.1 * sf1_ ) axes_0.annotate( "", xy=arrow_xy_, xytext=arrow_xy_ + arrow_dxy_ * sf2_, transform=axes_0.transAxes, arrowprops=dict(arrowstyle=my_arrow_style, color=color_, lw=3), ) plt.text( *motion_xy_, "motion", color=color_, fontsize=16, rotation=motion_angle_, transform=axes_0.transAxes, horizontalalignment="center", verticalalignment="center", ) return (axes_0, posn_0)
def plot_arrows(curves, G, pos, ax, edge_weight_scale): for line, (edge, val) in zip(curves, G.edges.items()): if edge[0] == edge[1]: continue mask = (~np.isnan(line)).all(axis=1) line = line[mask, :] if not len(line): # can be all NaNs continue line = line.reshape((-1, 2)) X, Y = line[:, 0], line[:, 1] node_start = pos[edge[0]] # reverse if np.where(np.isclose(node_start - line, [0, 0]).all(axis=1))[0][0]: X, Y = X[::-1], Y[::-1] mid = len(X) // 2 posA, posB = zip(X[mid:mid + 2], Y[mid:mid + 2]) # noqa arrow = FancyArrowPatch( posA=posA, posB=posB, # we clip because too small values # cause it to crash arrowstyle=ArrowStyle.CurveFilledB( head_length=np.clip( val["weight"] * edge_weight_scale * 4, _min_edge_weight, edge_width_limit, ), head_width=np.clip( val["weight"] * edge_weight_scale * 2, _min_edge_weight, edge_width_limit, ), ), color="k", zorder=float("inf"), alpha=edge_alpha, linewidth=0, ) ax.add_artist(arrow)
def draw_route(self, cur, table_name, route): fig, ax = self.draw_plots(cur, table_name) lats = [] lons = [] for i in range(len(route)): node = str(route[i]) cur.execute(f"SELECT * FROM {table_name} where id = {node}") node_data = cur.fetchone() lons.append(node_data[7]) lats.append(node_data[6]) if len(lats) > 1: ax.annotate('', xy=(lons[-1], lats[-1]), xytext=(lons[-2], lats[-2]), arrowprops=dict(arrowstyle=ArrowStyle( '<|-', head_length=0.3, head_width=0.15))) ax.scatter(lons, lats, s=2) ax.plot(lons, lats, color='red') plt.savefig('../data/route_img.png') return fig, ax
def draw(self, ax=None): self.ax = ax or self.ax or plt.gca() self.arrow = FancyArrowPatch( posA=(self.posA if not self.outer else (self.posA * self.stretch_outer)) * self.r, posB=(self.posB if not self.outer else (self.posB * self.stretch_outer)) * self.r, arrowstyle=ArrowStyle(self.arrowstyle, head_length=self.head_length, head_width=self.head_width), shrinkA=(self.shrinkA * (self.stretch_outer**2 if self.outer else 1)), shrinkB=(self.shrinkB * (self.stretch_outer**2 if self.outer else 1)), connectionstyle=self.connectionstyle if not self.outer else self.outer_connectionstyle, linewidth=self.edgewidth, color=self.edgecolor) self.ax.add_patch(self.arrow) if self.label: verts = self.arrow.get_path().vertices point = verts[1] norm = np.linalg.norm(point) self.ax.text( *((self.xytext if self.xytext is not None else point) * (self.stretch_inner if self.inner else 1.12)), self.label, horizontalalignment='center', verticalalignment='center', bbox=dict(facecolor=self.label_facecolor, edgecolor=self.label_edgecolor, alpha=0), color=self.label_color, fontname=self.fontname, fontsize=self.fontsize)
def add_arrows(axis, arrow_len): axis_arrow_length = arrow_len arrow = ArrowStyle("Fancy", head_length=0.4, head_width=0.2) arrow = 'simple' s1 = Arrow3D([-0.01, axis_arrow_length], [0, 0], [0, 0], mutation_scale=20, lw=1, arrowstyle=arrow, color="k") s2 = Arrow3D([0, 0], [-0.01, axis_arrow_length], [0, 0], mutation_scale=20, lw=1, arrowstyle=arrow, color="k") s3 = Arrow3D([0, 0], [0, 0], [-0.01, axis_arrow_length], mutation_scale=20, lw=1, arrowstyle=arrow, color="k") axis.add_artist(s1) axis.add_artist(s2) axis.add_artist(s3)
def __init__(self, transform, label_x, label_y, length=0.15, fontsize=0.08, loc=2, angle=0, aspect_ratio=1, pad=0.4, borderpad=0.4, frameon=False, color='w', alpha=1, sep_x=0.01, sep_y=0, fontproperties=None, back_length=0.15, head_width=10, head_length=15, tail_width=2, text_props=None, arrow_props=None, **kwargs): """ Draw two perpendicular arrows to indicate directions. Parameters ---------- transform : `matplotlib.transforms.Transform` The transformation object for the coordinate system in use, i.e., :attr:`matplotlib.axes.Axes.transAxes`. label_x, label_y : str Label text for the x and y arrows length : float, optional, default: 0.15 Length of the arrow, given in coordinates of *transform*. fontsize : float, optional, default: 0.08 Size of label strings, given in coordinates of *transform*. loc : int, optional, default: 2 Location of the direction arrows. Valid location codes are:: 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10 angle : float, optional, default: 0 The angle of the arrows in degrees. aspect_ratio : float, optional, default: 1 The ratio of the length of arrow_x and arrow_y. Negative numbers can be used to change the direction. pad : float, optional, default: 0.4 Padding around the labels and arrows, in fraction of the font size. borderpad : float, optional, default: 0.4 Border padding, in fraction of the font size. frameon : bool, optional, default: False If True, draw a box around the arrows and labels. color : str, optional, default: 'white' Color for the arrows and labels. alpha : float, optional, default: 1 Alpha values of the arrows and labels sep_x, sep_y : float, optional, default: 0.01 and 0 respectively Separation between the arrows and labels in coordinates of *transform*. fontproperties : `matplotlib.font_manager.FontProperties`, optional Font properties for the label text. back_length : float, optional, default: 0.15 Fraction of the arrow behind the arrow crossing. head_width : float, optional, default: 10 Width of arrow head, sent to ArrowStyle. head_length : float, optional, default: 15 Length of arrow head, sent to ArrowStyle. tail_width : float, optional, default: 2 Width of arrow tail, sent to ArrowStyle. text_props, arrow_props : dict Properties of the text and arrows, passed to `.textpath.TextPath` and `.patches.FancyArrowPatch`. **kwargs Keyworded arguments to pass to :class:`matplotlib.offsetbox.AnchoredOffsetbox`. Attributes ---------- arrow_x, arrow_y : `matplotlib.patches.FancyArrowPatch` Arrow x and y text_path_x, text_path_y : `matplotlib.textpath.TextPath` Path for arrow labels p_x, p_y : `matplotlib.patches.PathPatch` Patch for arrow labels box : `matplotlib.offsetbox.AuxTransformBox` Container for the arrows and labels. Notes ----- If *prop* is passed as a keyword argument, but *fontproperties* is not, then *prop* is be assumed to be the intended *fontproperties*. Using both *prop* and *fontproperties* is not supported. Examples -------- >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from mpl_toolkits.axes_grid1.anchored_artists import ( ... AnchoredDirectionArrows) >>> fig, ax = plt.subplots() >>> ax.imshow(np.random.random((10, 10))) >>> arrows = AnchoredDirectionArrows(ax.transAxes, '111', '110') >>> ax.add_artist(arrows) >>> fig.show() Using several of the optional parameters, creating downward pointing arrow and high contrast text labels. >>> import matplotlib.font_manager as fm >>> fontprops = fm.FontProperties(family='monospace') >>> arrows = AnchoredDirectionArrows(ax.transAxes, 'East', 'South', ... loc='lower left', color='k', ... aspect_ratio=-1, sep_x=0.02, ... sep_y=-0.01, ... text_props={'ec':'w', 'fc':'k'}, ... fontproperties=fontprops) """ if arrow_props is None: arrow_props = {} if text_props is None: text_props = {} arrowstyle = ArrowStyle("Simple", head_width=head_width, head_length=head_length, tail_width=tail_width) if fontproperties is None and 'prop' in kwargs: fontproperties = kwargs.pop('prop') if 'color' not in arrow_props: arrow_props['color'] = color if 'alpha' not in arrow_props: arrow_props['alpha'] = alpha if 'color' not in text_props: text_props['color'] = color if 'alpha' not in text_props: text_props['alpha'] = alpha t_start = transform t_end = t_start + transforms.Affine2D().rotate_deg(angle) self.box = AuxTransformBox(t_end) length_x = length length_y = length * aspect_ratio self.arrow_x = FancyArrowPatch((0, back_length * length_y), (length_x, back_length * length_y), arrowstyle=arrowstyle, shrinkA=0.0, shrinkB=0.0, **arrow_props) self.arrow_y = FancyArrowPatch((back_length * length_x, 0), (back_length * length_x, length_y), arrowstyle=arrowstyle, shrinkA=0.0, shrinkB=0.0, **arrow_props) self.box.add_artist(self.arrow_x) self.box.add_artist(self.arrow_y) text_path_x = TextPath( (length_x + sep_x, back_length * length_y + sep_y), label_x, size=fontsize, prop=fontproperties) self.p_x = PathPatch(text_path_x, transform=t_start, **text_props) self.box.add_artist(self.p_x) text_path_y = TextPath((length_x * back_length + sep_x, length_y * (1 - back_length) + sep_y), label_y, size=fontsize, prop=fontproperties) self.p_y = PathPatch(text_path_y, **text_props) self.box.add_artist(self.p_y) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=self.box, frameon=frameon, **kwargs)
def _visualize(self, filename=None, transparent=True): env = self.env fig, ax = plt.subplots(1) [p.remove() for p in reversed(ax.patches)] # Draw boundaries plt.plot([0, 0], [-10, 10], linewidth=5, color='k') plt.plot([9, 9], [-10, 10], linewidth=5, color='k') plt.axis('square') plt.axis('off') plt.xlim((-1, 10)) plt.ylim((-6, 5)) # Car # Pose of the end of the car car = env.x.copy() car = Rectangle((car[0], car[1]), 0.3, env.car_length, angle=np.rad2deg(env.angle), color=colors[-1]) plt.gca().add_patch(car) # pedestrians pedestrians = env.pedestrians pedestrian_angles = self.weighted_directions pedestrian_directions = self.weighted_directions * 5.0 angles = self.expected_angles belief = self.belief for i in range(len(pedestrians)): ped = Circle(pedestrians[i], radius=0.2, color=colors[i], zorder=20) plt.gca().add_patch(ped) style = ArrowStyle.Simple(head_length=1, head_width=1, tail_width=1) xy = pedestrians[i] for j in range(3): dxdy = get_pedestrian_directions(self.pedestrian_speeds[i], angles[i, j])[0] * 5.0 arrow = Arrow(xy[0], xy[1], dxdy[0], dxdy[1], color=colors[i], linewidth=0, width=0.3, alpha=belief[i, j], fill=True) # print(belief[i,j]) # arrow = FancyArrowPatch(posA=xy, posB=xy+dxdy, arrowstyle='simple', color=colors[i], alpha=belief[i, j], linewidth=1.0) plt.gca().add_patch(arrow) arrow = Arrow( xy[0], xy[1], dxdy[0], dxdy[1], edgecolor=colors[i], width=0.3, linewidth=0.5, fill=False, ) plt.gca().add_patch(arrow) if filename is not None: plt.savefig(filename, bbox_inches='tight', transparent=transparent)
header=0) nbs = [i for i in range(len(dfs.index))] cats = dfcat.loc[dfg.index] motors = cats.index[cats['Category'] == 'MOTOR'] inters = cats.index[cats['Category'] == 'INTERNEURON'] sensors = cats.index[cats['Category'] == 'SENSORY'] """ Preferences : you can change the shape and colors of neuron categories here """ SENSOR_COLOR = '#006000' SENSOR_SHAPE = 'o' INTER_COLOR = '#000060' INTER_SHAPE = 'o' MOTOR_COLOR = '#600000' MOTOR_SHAPE = 'o' NODE_SIZE = 2500 style = ArrowStyle("wedge", tail_width=2., shrink_factor=0.2) styleg = ArrowStyle("wedge", tail_width=0.6, shrink_factor=0.4) CONN_STYLE = 'arc3, rad=0.3' def connections(neuron='BAGL', connstyle=CONN_STYLE): '''Prepare graph for plotting''' G = nx.DiGraph() syn_in = dfs.index[dfs[neuron] > 0].tolist() intens_in = dfs.loc[dfs[neuron] > 0, neuron] syni = [(pre, neuron, {}) for pre in syn_in] G.add_edges_from(syni) gaps_ = dfg.index[dfg[neuron] > 0].tolist() intens_g = 0.1 * dfg.loc[dfg[neuron] > 0, neuron]
def draw(self, graph, *args, **kwds): # NOTE: matplotlib has numpy as a dependency, so we can use it in here import matplotlib as mpl import matplotlib.markers as mmarkers from matplotlib.path import Path from matplotlib.patches import FancyArrowPatch from matplotlib.patches import ArrowStyle import numpy as np def shrink_vertex(ax, aux, vcoord, vsize_squared): """Shrink edge by vertex size""" aux_display, vcoord_display = ax.transData.transform([aux, vcoord]) d = sqrt(((aux_display - vcoord_display) ** 2).sum()) fr = sqrt(vsize_squared) / d end_display = vcoord_display + fr * (aux_display - vcoord_display) end = ax.transData.inverted().transform(end_display) return end def callback_factory(ax, vcoord, vsizes, arrows): def callback_edge_offset(event): for arrow, src, tgt in arrows: v1, v2 = vcoord[src], vcoord[tgt] # This covers both cases (curved and straight) aux1, aux2 = arrow._path_original.vertices[[1, -2]] start = shrink_vertex(ax, aux1, v1, vsizes[src]) end = shrink_vertex(ax, aux2, v2, vsizes[tgt]) arrow._path_original.vertices[0] = start arrow._path_original.vertices[-1] = end return callback_edge_offset ax = self.ax # FIXME: deal with unnamed *args # Get layout layout = kwds.get("layout", graph.layout()) if isinstance(layout, str): layout = graph.layout(layout) # Vertex coordinates vcoord = layout.coords # Vertex properties nv = graph.vcount() # Vertex size vsizes = kwds.get("vertex_size", 5) # Enforce numpy array for sizes, because (1) we need the square and (2) # they are needed to calculate autoshrinking of edges if np.isscalar(vsizes): vsizes = np.repeat(vsizes, nv) else: vsizes = np.asarray(vsizes) # ax.scatter uses the *square* of diameter vsizes **= 2 # Vertex color c = kwds.get("vertex_color", "steelblue") # Vertex opacity alpha = kwds.get("alpha", 1.0) # Vertex labels label = kwds.get("vertex_label", None) # Vertex label size label_size = kwds.get("vertex_label_size", mpl.rcParams["font.size"]) # Vertex zorder vzorder = kwds.get("vertex_order", 2) # Vertex shapes # mpl shapes use slightly different names from Cairo, but we want the # API to feel consistent, so we use a conversion dictionary shapes = kwds.get("vertex_shape", "o") if shapes is not None: if isinstance(shapes, str): shapes = self._shape_dict.get(shapes, shapes) elif isinstance(shapes, mmarkers.MarkerStyle): pass # Scatter vertices x, y = list(zip(*vcoord)) ax.scatter(x, y, s=vsizes, c=c, marker=shapes, zorder=vzorder, alpha=alpha) # Vertex labels if label is not None: for i, lab in enumerate(label): xi, yi = x[i], y[i] ax.text(xi, yi, lab, fontsize=label_size) dx = max(x) - min(x) dy = max(y) - min(y) ax.set_xlim(min(x) - 0.05 * dx, max(x) + 0.05 * dx) ax.set_ylim(min(y) - 0.05 * dy, max(y) + 0.05 * dy) # Edge properties ne = graph.ecount() ec = kwds.get("edge_color", "black") edge_width = kwds.get("edge_width", 1) arrow_width = kwds.get("edge_arrow_width", 2) arrow_length = kwds.get("edge_arrow_size", 4) ealpha = kwds.get("edge_alpha", 1.0) ezorder = kwds.get("edge_order", 1.0) try: ezorder = float(ezorder) ezorder = [ezorder] * ne except TypeError: pass # Decide whether we need to calculate the curvature of edges # automatically -- and calculate them if needed. autocurve = kwds.get("autocurve", None) if autocurve or ( autocurve is None and "edge_curved" not in kwds and "curved" not in graph.edge_attributes() and graph.ecount() < 10000 ): from igraph import autocurve default = kwds.get("edge_curved", 0) if default is True: default = 0.5 default = float(default) kwds["edge_curved"] = autocurve(graph, attribute=None, default=default) # Arrow style for directed and undirected graphs if graph.is_directed(): arrowstyle = ArrowStyle( "-|>", head_length=arrow_length, head_width=arrow_width, ) else: arrowstyle = "-" # Edge coordinates and curvature nloops = [0 for x in range(ne)] has_curved = "curved" in graph.es.attributes() arrows = [] for ie, edge in enumerate(graph.es): src, tgt = edge.source, edge.target x1, y1 = vcoord[src] x2, y2 = vcoord[tgt] # Loops require special treatment if src == tgt: # Find all non-loop edges nloopstot = 0 angles = [] for tgtn in graph.neighbors(src): if tgtn == src: nloopstot += 1 continue xn, yn = vcoord[tgtn] angles.append(180.0 / pi * atan2(yn - y1, xn - x1) % 360) # with .neighbors(mode=ALL), which is default, loops are double # counted nloopstot //= 2 angles = sorted(set(angles)) # Only loops or one non-loop if len(angles) < 2: ashift = angles[0] if angles else 270 if nloopstot == 1: # Only one self loop, use a quadrant only angles = [(ashift + 135) % 360, (ashift + 225) % 360] else: nshift = 360.0 / nloopstot angles = [ (ashift + nshift * nloops[src]) % 360, (ashift + nshift * (nloops[src] + 1)) % 360, ] nloops[src] += 1 else: angles.append(angles[0] + 360) idiff = 0 diff = 0 for i in range(len(angles) - 1): diffi = abs(angles[i + 1] - angles[i]) if diffi > diff: idiff = i diff = diffi angles = angles[idiff : idiff + 2] ashift = angles[0] nshift = (angles[1] - angles[0]) / nloopstot angles = [ (ashift + nshift * nloops[src]), (ashift + nshift * (nloops[src] + 1)), ] nloops[src] += 1 # this is not great, but alright angspan = angles[1] - angles[0] if angspan < 180: angmid1 = angles[0] + 0.1 * angspan angmid2 = angles[1] - 0.1 * angspan else: angmid1 = angles[0] + 0.5 * (angspan - 180) + 45 angmid2 = angles[1] - 0.5 * (angspan - 180) - 45 aux1 = ( x1 + 0.2 * dx * cos(pi / 180 * angmid1), y1 + 0.2 * dy * sin(pi / 180 * angmid1), ) aux2 = ( x1 + 0.2 * dx * cos(pi / 180 * angmid2), y1 + 0.2 * dy * sin(pi / 180 * angmid2), ) start = shrink_vertex(ax, aux1, (x1, y1), vsizes[src]) end = shrink_vertex(ax, aux2, (x2, y2), vsizes[tgt]) path = Path( [start, aux1, aux2, end], # Cubic bezier by mpl codes=[1, 4, 4, 4], ) else: curved = edge["curved"] if has_curved else False if curved: aux1 = (2 * x1 + x2) / 3.0 - edge.curved * 0.5 * (y2 - y1), ( 2 * y1 + y2 ) / 3.0 + edge.curved * 0.5 * (x2 - x1) aux2 = (x1 + 2 * x2) / 3.0 - edge.curved * 0.5 * (y2 - y1), ( y1 + 2 * y2 ) / 3.0 + edge.curved * 0.5 * (x2 - x1) start = shrink_vertex(ax, aux1, (x1, y1), vsizes[src]) end = shrink_vertex(ax, aux2, (x2, y2), vsizes[tgt]) path = Path( [start, aux1, aux2, end], # Cubic bezier by mpl codes=[1, 4, 4, 4], ) else: start = shrink_vertex(ax, (x2, y2), (x1, y1), vsizes[src]) end = shrink_vertex(ax, (x1, y1), (x2, y2), vsizes[tgt]) path = Path([start, end], codes=[1, 2]) arrow = FancyArrowPatch( path=path, arrowstyle=arrowstyle, lw=edge_width, color=ec, alpha=ealpha, zorder=ezorder[ie], ) ax.add_artist(arrow) # Store arrows and their sources and targets for autoscaling arrows.append((arrow, src, tgt)) # Autoscaling during zoom, figure resize, reset axis limits callback = callback_factory(ax, vcoord, vsizes, arrows) ax.get_figure().canvas.mpl_connect("resize_event", callback) ax.callbacks.connect("xlim_changed", callback) ax.callbacks.connect("ylim_changed", callback)
from matplotlib.font_manager import FontProperties from matplotlib.offsetbox import HPacker, TextArea, AnnotationBbox from matplotlib.patches import FancyArrowPatch, ArrowStyle, Polygon from matplotlib.ticker import NullFormatter, NullLocator, MaxNLocator from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy.stats import scoreatpercentile from fluff.color import create_colormap from fluff.config import FONTSIZE from fluff.fluffio import load_annotation from fluff.track import Track DEFAULT_COLORS = ["#e41a1c", "#4daf4a", "#377eb8"] GENE_ARROW = "->" GENE_ARROW = ArrowStyle._Curve(beginarrow=False, endarrow=True, head_length=.4, head_width=.4) def colortext(x, y, texts, colors, **kwargs): pos = {"right": 1, "center": 0.5, "left": 0, "top": 0, "bottom": 1} ax = kwargs.get("ax") verticalalignment = pos[kwargs.get("verticalalignment", "center")] horizontalalignment = pos[kwargs.get("horizontalalignment", "center")] annotation_clip = kwargs.get("clip_on", False) fontproperties = kwargs.get("fontproperties", None) textprops = {"fontproperties": fontproperties} transform = kwargs.get("transform", None) areas = []
def plot_network(network, n_columns=1, n_regions=1, radius=None, ax=None, linewidth=2, cmap=None, clim=None): """This plot the columnar network""" from matplotlib.patches import ArrowStyle ax = plt.subplot() if ax is None else ax cmap = plt.get_cmap('bwr') if cmap is None else cmap clim = [-1, 1] if clim is None else clim # network is made of n_columns + entry node n_nodes = (len(network) // n_columns - 1) // n_regions init_pos = np.zeros((network.shape[0], 2)) x = np.linspace(-1, 1, n_regions) y = np.linspace(-1, 1, n_columns) if radius is None: radius = 1. / n_columns z = np.linspace(-np.pi / 2, 3 * np.pi / 2, n_nodes + 1)[:-1] z = np.transpose([np.cos(z), np.sin(z) + 1.]) for column, region, node in itertools.product(range(n_columns), range(n_regions), range(-1, n_nodes)): sel = select_nodes(n_columns, n_regions, n_nodes=n_nodes, column=column, region=region, node=node) if node == -1: first_node = np.diff(x[:2]) if len(x) > 1 else 1. init_pos[sel, 0] = -1 - first_node init_pos[sel, 1] = y[column] - 1 * radius else: init_pos[sel, 0] = x[region] + z[node, 0] * radius init_pos[sel, 1] = y[column] + z[node, 1] * radius arrow_style = ArrowStyle.Fancy(head_length=1., head_width=1.25, tail_width=.25) G, nodes, = plot_graph(network, iterations=0, edge_curve=True, directional=True, node_color='w', node_alpha=1., edge_color=cmap, negative_weights=True, init_pos=init_pos.T, ax=ax, final_pos=None, node_size=linewidth * 100, edge_width=linewidth, self_edge=1000, clim=clim, arrowstyle=arrow_style) nodes.set_linewidths(linewidth) ax.set_aspect('equal') ax.patch.set_visible(False) if n_columns > 1: ax.set_ylim([-.2, 1.2]) if n_regions > 1: ax.set_xlim([-.2, 1.2])
def draw_networkx_arrows( G, pos, edgelist=None, nodedim=0.0, width=0.02, # width=0.02, 1.0 widthscale=1.0, edge_color="k", style="solid", alphas=1.0, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, label=[None], pathstyle="straight", **kwds): if ax is None: ax = plt.gca() if edgelist is None: edgelist = G.edges() if width is None: try: widthlist = np.array( list([(widthscale * prop["freq"]) for (u, v, prop) in G.edges(data=True)])) widthlist = widthscale * widthlist / np.max(widthlist) # widthlist = [(a+widthscale*0.1) for a in widthlist] ## this was # giving colour to non-existent edges except BaseException: # widthlist = widthscale*0.02 widthlist = widthscale else: widthlist = width if not edgelist or len(edgelist) == 0: # no edges! return None if len(alphas) < len(edgelist): alphas = np.repeat(alphas, len(edgelist)) # set edge positions edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist]) if not cb.iterable(widthlist): lw = (widthlist, ) else: lw = widthlist if ( # not cb.is_string_like(edge_color) type(edge_color) != str and cb.iterable(edge_color) and len(edge_color) == len(edge_pos)): if np.alltrue([type(c) == str for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple( [colorConverter.to_rgba(c) for c in edge_color]) elif np.alltrue( # [not cb.is_string_like(c) for c in edge_color] [type(c) != str for c in edge_color]): # If color specs are given as (rgb) or (rgba) tuples, we're OK if np.alltrue( [cb.iterable(c) and len(c) in (3, 4) for c in edge_color]): edge_colors = tuple(edge_color) else: # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError("edge_color must consist of \ either color names or numbers") else: if ( # cb.is_string_like(edge_color) type(edge_color) == str or len(edge_color) == 1): edge_colors = (colorConverter.to_rgba(edge_color), ) else: raise ValueError("edge_color must be a single color or \ list of exactly m colors where m is the number or edges") edge_collection = collections.LineCollection(edge_pos, colors=edge_colors, linewidths=lw) edge_collection.set_zorder(1) # edges go behind nodes # ax.add_collection(edge_collection) if edge_colors is None: if edge_cmap is not None: assert isinstance(edge_cmap, Colormap) edge_collection.set_array(np.asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() max_bayes_value = max(edge_collection.get_clim()) edge_collection.set_clim(0.5, max_bayes_value) # for i in range(len(edgelist)): # print(edgelist[i], ":", edge_color[i]) for n in G: c = Circle(pos[n], radius=0.02, alpha=0.5) ax.add_patch(c) G.node[n]["patch"] = c x, y = pos[n] seen = {} # Rescale all weights between 0,1 so cmap can find the appropriate RGB # value. offset = 0.7 norm_edge_color = edge_color / max_bayes_value # print("all color cmap values", norm_edge_color) if G.is_directed(): seen = {} for idx in range(len(edgelist)): if not cb.iterable(widthlist): lw = widthlist else: lw = widthlist[idx] arrow_colour = edge_cmap(norm_edge_color[idx]) if pathstyle is "straight": (src, dst) = edge_pos[idx] x1, y1 = src x2, y2 = dst delta = 0.2 theta = np.arctan((y2 - y1) / (x2 - x1)) # print(theta) if x1 == x2: dx = x2 - x1 dy = y2 - y1 - np.sign(y2 - y1) * delta elif y1 == y2: dx = x2 - x1 - np.sign(x2 - x1) * delta dy = y2 - y1 else: dx = (x2 - x1 - np.sign(x2 - x1) * np.abs(np.cos(theta) * delta) ) # x offset dy = (y2 - y1 - np.sign(y2 - y1) * np.abs(np.sin(theta) * delta) ) # y offset thislabel = None if len(label) < len(edgelist) else label[idx] ax.arrow( x1, y1, dx, dy, facecolor=arrow_colour, alpha=alphas[idx], linewidth=0, antialiased=True, width=lw, head_width=5 * lw, overhang=-5 * 0.02 / lw, length_includes_head=True, label=thislabel, zorder=1, ) elif pathstyle is "curve": (u, v) = edgelist[idx] # (u,v,prop) = prop['weight'] for in list_of_edges # flipped = G.edge[(u,v)] winner = G.edges[(u, v)]["winner"] loser = G.edges[(u, v)]["loser"] n1 = G.node[winner]["patch"] n2 = G.node[loser]["patch"] # n1=G.node[loser]['patch'] # n2=G.node[winner]['patch'] # n1=G.node[u]['patch'] # n2=G.node[v]['patch'] rad = 0.1 if (u, v) in seen: rad = seen.get((u, v)) rad = (rad + np.sign(rad) * 0.1) * -1 alpha = 0.5 kwargs = { # 'head_width': 5*lw, "facecolor": arrow_colour[0:3] + (alphas[idx], ), "edgecolor": (0, 0, 0, 0.0) # 'overhang':-5*0.02/lw, # 'length_includes_head': True, # capstyle='projecting', } # Can be accepted by fancy arrow patch to alter arrows arrow_style = ArrowStyle.Wedge(tail_width=lw, shrink_factor=0.4) # arrow_style = mpatches.ArrowStyle.Curve( # ) e = FancyArrowPatch( n1.center, n2.center, patchA=n1, patchB=n2, arrowstyle=arrow_style, # arrowstyle='simple', # arrowstyle='curveb', connectionstyle="arc3,rad=%s" % rad, mutation_scale=5.0, # alpha=0.5, lw=lw, # AROUND 10 TO BE FEASIBLE **kwargs) seen[(u, v)] = rad ax.add_patch(e) # print("rad", rad) # print("Node coordinates", n1, n2) # print("arrowcolor", arrow_colour) # update view minx = np.amin(np.ravel(edge_pos[:, :, 0])) maxx = np.amax(np.ravel(edge_pos[:, :, 0])) miny = np.amin(np.ravel(edge_pos[:, :, 1])) maxy = np.amax(np.ravel(edge_pos[:, :, 1])) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() return edge_collection
def plot_2D(self, ticket, var_x, var_y, title, xtitle, ytitle, xum="", yum="", plotting_range=None, use_default_factor=True): matplotlib.rcParams['axes.formatter.useoffset'] = 'False' if use_default_factor: factor1 = SRWPlot.get_factor(var_x) factor2 = SRWPlot.get_factor(var_y) else: factor1 = 1.0 factor2 = 1.0 if plotting_range == None: xx = ticket['bin_h'] yy = ticket['bin_v'] nbins_h = ticket['nbins_h'] nbins_v = ticket['nbins_v'] histogram = ticket['histogram'] else: range_x = numpy.where( numpy.logical_and(ticket['bin_h'] >= plotting_range[0], ticket['bin_h'] <= plotting_range[1])) range_y = numpy.where( numpy.logical_and(ticket['bin_v'] >= plotting_range[2], ticket['bin_v'] <= plotting_range[3])) xx = ticket['bin_h'][range_x] yy = ticket['bin_v'][range_y] histogram = [] for row in ticket['histogram'][range_x]: histogram.append(row[range_y]) nbins_h = len(xx) nbins_v = len(yy) if len(xx) == 0 or len(yy) == 0: raise Exception("Nothing to plot in the given range") xmin, xmax = xx.min(), xx.max() ymin, ymax = yy.min(), yy.max() origin = (xmin * factor1, ymin * factor2) scale = (abs( (xmax - xmin) / nbins_h) * factor1, abs( (ymax - ymin) / nbins_v) * factor2) # PyMCA inverts axis!!!! histogram must be calculated reversed data_to_plot = [] for y_index in range(0, nbins_v): x_values = [] for x_index in range(0, nbins_h): x_values.append(histogram[x_index][y_index]) data_to_plot.append(x_values) self.plot_canvas.setImage(numpy.array(data_to_plot), origin=origin, scale=scale) if xtitle is None: xtitle = SRWPlot.get_SRW_label(var_x) if ytitle is None: ytitle = SRWPlot.get_SRW_label(var_y) self.plot_canvas.setGraphXLabel(xtitle) self.plot_canvas.setGraphYLabel(ytitle) self.plot_canvas.setGraphTitle(title) self.plot_canvas._histoHPlot.setGraphYLabel('Frequency') self.plot_canvas._histoHPlot._backend.ax.xaxis.get_label( ).set_color('white') self.plot_canvas._histoHPlot._backend.ax.xaxis.get_label( ).set_fontsize(1) for label in self.plot_canvas._histoHPlot._backend.ax.xaxis.get_ticklabels( ): label.set_color('white') label.set_fontsize(1) self.plot_canvas._histoVPlot.setGraphXLabel('Frequency') self.plot_canvas._histoVPlot._backend.ax.yaxis.get_label( ).set_color('white') self.plot_canvas._histoVPlot._backend.ax.yaxis.get_label( ).set_fontsize(1) for label in self.plot_canvas._histoVPlot._backend.ax.yaxis.get_ticklabels( ): label.set_color('white') label.set_fontsize(1) if ticket['fwhm_h'] == None: ticket['fwhm_h'] = 0.0 if ticket['fwhm_v'] == None: ticket['fwhm_v'] = 0.0 n_patches = len(self.plot_canvas._histoHPlot._backend.ax.patches) if (n_patches > 0): self.plot_canvas._histoHPlot._backend.ax.patches.remove( self.plot_canvas._histoHPlot._backend.ax.patches[n_patches - 1]) if not ticket['fwhm_h'] == 0.0: x_fwhm_i, x_fwhm_f = ticket['fwhm_coordinates_h'] x_fwhm_i, x_fwhm_f = x_fwhm_i * factor1, x_fwhm_f * factor1 y_fwhm = max(ticket['histogram_h']) * 0.5 self.plot_canvas._histoHPlot._backend.ax.add_patch( FancyArrowPatch([x_fwhm_i, y_fwhm], [x_fwhm_f, y_fwhm], arrowstyle=ArrowStyle.CurveAB( head_width=2, head_length=4), color='b', linewidth=1.5)) n_patches = len(self.plot_canvas._histoVPlot._backend.ax.patches) if (n_patches > 0): self.plot_canvas._histoVPlot._backend.ax.patches.remove( self.plot_canvas._histoVPlot._backend.ax.patches[n_patches - 1]) if not ticket['fwhm_v'] == 0.0: y_fwhm_i, y_fwhm_f = ticket['fwhm_coordinates_v'] y_fwhm_i, y_fwhm_f = y_fwhm_i * factor2, y_fwhm_f * factor2 x_fwhm = max(ticket['histogram_v']) * 0.5 self.plot_canvas._histoVPlot._backend.ax.add_patch( FancyArrowPatch([x_fwhm, y_fwhm_i], [x_fwhm, y_fwhm_f], arrowstyle=ArrowStyle.CurveAB( head_width=2, head_length=4), color='r', linewidth=1.5)) self.plot_canvas._histoHPlot.replot() self.plot_canvas._histoVPlot.replot() self.plot_canvas.replot() self.info_box.total.setText("{:.3e}".format( decimal.Decimal(ticket['total']))) self.info_box.fwhm_h.setText("{:5.4f}".format(ticket['fwhm_h'] * factor1)) self.info_box.fwhm_v.setText("{:5.4f}".format(ticket['fwhm_v'] * factor2)) self.info_box.label_h.setText("FWHM " + xum) self.info_box.label_v.setText("FWHM " + yum)
import numpy as np from matplotlib.font_manager import FontProperties from matplotlib.offsetbox import HPacker, TextArea, AnnotationBbox from matplotlib.patches import FancyArrowPatch, ArrowStyle, Polygon from matplotlib.ticker import NullFormatter, NullLocator, MaxNLocator from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy.stats import scoreatpercentile from fluff.color import create_colormap from fluff.config import FONTSIZE from fluff.fluffio import load_annotation from fluff.track import Track DEFAULT_COLORS = ["#e41a1c", "#4daf4a", "#377eb8"] GENE_ARROW = "->" GENE_ARROW = ArrowStyle._Curve(beginarrow=False, endarrow=True, head_length=.4, head_width=.4) def colortext(x, y, texts, colors, **kwargs): pos = { "right": 1, "center": 0.5, "left": 0, "top": 0, "bottom": 1 } ax = kwargs.get("ax") verticalalignment = pos[kwargs.get("verticalalignment", "center")] horizontalalignment = pos[kwargs.get("horizontalalignment", "center")] annotation_clip = kwargs.get("clip_on", False) fontproperties = kwargs.get("fontproperties", None)
def main(): path = 'C:/Users/97899/Desktop/N/N_year/' # 各物种环的数量 for year in range(2018, 2019): D = {} path1 = path + "N_" + str(year) + '/Assemb/' + str(year) + '-' + str( 0) + '.txt' Specise_set = LoadDict(path1) path3 = path + "N_" + str(year) + '/Spearman/' + str(year) + '-' + str( 0) + '.txt' Spear_set = LoadDict(path3) for ex in range(33, 34): D[ex] = {} ex = float(ex) path2 = path + "N_" + str(year) + '/CPmat/' + str( year) + '-' + str(ex) + '.txt' CP_mat = LoadDict(path2) if year < 2016: C_mat, Ass = Select_Zuhe(CP_mat, Specise_set[str(ex)], Spear_set[str(ex)]) else: C_mat, Ass = Select_Zuhe(CP_mat, Specise_set[ex], Spear_set[ex]) if np.all(C_mat == 0): D[ex] = {3: -0.15} else: # ['灰绿藜'Chenopodium glaucum , '羽茅'Achnatherum sibiricum, '糙隐子草'leistogenes squarrosa, # '星毛委陵菜'Potentilla acaulis, '冰草'Agropyron cristatum, '大针茅'Stipa grandis] print("Ass", Ass) node_list = Ass = [ 'Chenopodium\nglaucum', 'Achnatherum\nsibiricum', 'Cleistogenes\nsquarrosa', 'Potentilla\nacaulis', 'Agropyron\ncristatum', 'Stipa\ngrandis' ] # node_list=['灰绿藜','羽茅','糙隐子草','星毛委陵菜','冰草','大针茅'] # print(node_list) plt.rcParams['axes.unicode_minus'] = False plt.rcParams['font.sans-serif'] = ['Times New Roman'] # Times New Roman,SimHei G = nx.DiGraph() G.add_nodes_from(node_list) # 添加点a edge_list = get_all_edge(C_mat, node_list) print(edge_list) G.add_edges_from(edge_list) # 添加边,起点为x,终点为y cyc_sys = list(nx.simple_cycles(G)) # print(cyc_sys) '''显示图形''' # 结点分配不同的颜色 pos = nx.circular_layout(G) nx.draw_networkx_nodes(G, pos, node_color=[ "limegreen", "r", "violet", "cyan", "orange", "yellow" ], with_labels=True, node_size=500) # 构建文本标签字典 D_node = {} for ass in Ass: D_node[ass] = ass # 添加结点标签 nx.draw_networkx_labels(G, pos, labels=D_node, font_size=10) # 添加边 ArrowStyle("wedge,tail_width=0.1,shrink_factor=0.8") # nx.draw_networkx_edges(G, pos, edgelist=edge_list, edge_color='r', # arrows=True,arrowsize=9,arrowstyle="wedge") # nx.draw_networkx_edges(G, pos=nx.circular_layout(G),edgelist=edge_list, # edge_color='r',arrows=True) # nx.draw(G, pos=nx.circular_layout(G), node_color=["limegreen", "r", "violet", "cyan", "orange", "yellow"], # edge_color='red', with_labels=True,edgelist=[('糙隐子草', '糙隐子草'), ('星毛委陵菜', '糙隐子草')], # font_size=10, node_size=3000) edge_ring = [] # node_color = ["limegreen", "r", "violet", "cyan", "orange", "yellow"] # node_color = ["lawngreen","lawngreen","lawngreen","orange","lawngreen","lawngreen"] node_color = ["darkturquoise"] for item in cyc_sys: if len(item) >= 3: print(item) # if "Potentilla\nacaulis" in item: if "Potentilla\nacaulis" in item: print(item) edge_list1 = get_cyc_edge(C_mat, item, Ass) nx.draw(G, pos, node_color=node_color, edge_color='orange', with_labels=True, edgelist=edge_list1, width=1.5, font_size=10, node_size=3000) edge_ring.extend(edge_list1) # if "Potentilla\nacaulis" not in item: # edge_list2 = get_cyc_edge(C_mat, item, Ass) # nx.draw(G, pos, node_color=node_color, # edge_color='violet', with_labels=True, edgelist=edge_list2,width=4, # font_size=10, node_size=3000) # edge_ring.extend(edge_list2) edge_chain = set(edge_list) - set(edge_ring) nx.draw(G, pos, node_color=node_color, edge_color='springgreen', with_labels=True, edgelist=edge_chain, width=0.7, font_size=10, node_size=3000) plt.show()
def __init__(self): # Initialize parameters # Network parameters self.layers = pars.layers self.nodes = pars.nodes # Get data and initialize quantities and links self.start_at = (pars.start_sim - 2000) * pars.months self.end_at = (pars.end_sim - 2000) * pars.months self.c_vis = pars.c_vis self.trade_data = np.load(pars.data_path)[ self.start_at:self.end_at, :, :self.nodes, :self.nodes] self.quantities = [ np.sum(self.trade_data[0, 1, c, :]) for c in range(self.nodes) ] self.agg_exports = np.sum(self.trade_data[:, 1, :, :], axis=2) # since index 1 denotes exports self.agg_links = np.sum(self.trade_data, axis=0) self.links = self.trade_data[0, :, :, :] self.iterations = self.trade_data.shape[0] # Drawing parameters self.min_trade_size = pars.min_trade_size self.layer_names = ['Imports', 'Exports'] self.node_size_min = 0.01 self.node_font_sizes = int(12) self.mln_node_size = 0.3 self.node_size_scaling = 15000 self.link_size_scaling = 3.5 self.arrow = ArrowStyle('simple', head_length=10, head_width=10, tail_width=.75) self.mln_node_sizes = self.layers * self.nodes * [ self.mln_node_size * self.node_size_scaling ] self.dynamic_node_range = range(self.layers * self.nodes, (self.layers + 1) * self.nodes) self.colors = ['#003071', 'white', 'grey', '#731212'] self.layer_y_dist = 17 self.map_layer_dist = 17 self.mln_xlims = (-4, 4) self.mln_ylims = (-20, 30) self.img_size_orig = (1160, 644) self.img_size = (850, 335) self.img_zoom = 0.72 self.img_xy = [-0.5, -14] self.pll_x = [-3.1, 2.8, 3.3, -2.6] self.pll_y = [ y + self.map_layer_dist for y in [-19.4, -19.4, -8.4, -8.4] ] self.txt_ie_x = -4 self.txt_x = self.mln_xlims[0] self.txt_y = self.mln_ylims[1] self.font = 'verdana' self.txt_font_size = 20 self.dynamic_node_scale = 3 self.dynamic_node_lim_x_offset = 1 self.dynamic_node_lim_y_offset = 3 self.ax_3_xlims = (0, self.iterations) self.ax_3_ylims = (0, np.max(np.sum(self.agg_exports, axis=1)) * 1.1) self.tick_size = 13 self.label_font_size = 15 self.ax_3_lw = 1 # Set up the figure pylab.ion() self.dpi = 100 self.fig_size = (19.2, 10.8) self.resolution = [f * self.dpi for f in self.fig_size] self.fig = plt.figure(0, figsize=self.fig_size, dpi=self.dpi) self.fig.canvas.set_window_title('European System') self.ax_mln = plt.subplot2grid((10, 10), (0, 0), rowspan=10, colspan=5) self.ax_nodes = plt.subplot2grid((10, 10), (0, 5), rowspan=4, colspan=5) self.ax_3 = plt.subplot2grid((10, 10), (4, 6), rowspan=5, colspan=3) self.fig.tight_layout(pad=3, h_pad=1.25, w_pad=1.25)