def polyarc(arcs, color = 'b', linewidth=1, alpha=1, capstyle='butt', joinstyle='miter'): """ """ for arc in arcs: if abs(arc.d) < 1e-5: verts = [(arc.p0.x,arc.p0.y), (arc.p1.x,arc.p1.y)] codes = [Path.MOVETO, Path.LINETO] path = Path(verts, codes) arc = patches.PathPatch(path, linewidth = linewidth, edgecolor = color, facecolor = 'None', alpha = alpha) else: center,radius, angle0, angle1, negative = arc.to_conventional() angle0 = 180*angle0/math.pi angle1 = 180*angle1/math.pi if negative: angle0, angle1 = angle1, angle0 arc = Arc(center, 2*radius, 2*radius, 0, angle0, angle1, color=color, linewidth = linewidth, alpha=alpha) arc.set_path_effects([PathEffects.Stroke(capstyle=capstyle, joinstyle=joinstyle )]) plt.gca().add_artist(arc) plt.xticks([]) plt.yticks([])
def _path_to_parent(self, node): c = self.n2c[node]; theta1 = c.angle; r = c.depth M = Path.MOVETO; L = Path.LINETO pc = self.n2c[node.parent]; theta2 = pc.angle px1 = math.cos(math.radians(c.angle))*pc.depth py1 = math.sin(math.radians(c.angle))*pc.depth verts = [(c.x,c.y),(px1,py1)]; codes = [M,L] t1, t2 = tuple(sorted((theta1,theta2))) diam = pc.depth*2 arc = Arc((0,0), diam, diam, theta1=t1, theta2=t2) arcpath = arc.get_path() av = arcpath.vertices * pc.depth ac = arcpath.codes verts.extend(av.tolist()) codes.extend(ac.tolist()) return verts, codes
from matplotlib.patches import Wedge, Arc import matplotlib.pyplot as plt #вставить необходимые операторы n = 6 # размер области m = 5 # размер области plt.xlim(0, n) plt.ylim(0, m) ax = plt.gca() # нарисовать сектор figure_w = Wedge( (3, 1), 2, 45, 135 ) # сформировать сектор, параметры для цвета линии и заливки, а также толщины линии не указывать ax.add_patch(figure_w) # нарисовать дугу # дуга должна иметь определенную толщину (linewidth = 3), нулевой угол поворота, цвет не указывать figure_a = Arc((3, 1), 6, 6, 0, 45, 135, lw=3) # сформировать дугу ax.add_patch(figure_a) plt.show()
def _arc(i, j, width=1, linestyle='-', color='black'): """ Creating a single arc from i to j """ return Arc(((i+j)/2., 0.4), abs(i-j), abs(i-j), 0, 0, 180, linewidth=width, edgecolor=color, fill=False, linestyle=linestyle)
def draw_field(line_dist, center_dist, players=[], balls=[], ball_colors=[], ball_sizes=[], title=''): if balls and not ball_colors: ball_colors = ['green'] * len(balls) if balls and not ball_sizes: ball_sizes = [2] * len(balls) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) arc_center = (line_dist**2 - center_dist**2) / (line_dist * sqrt(2) - 2 * center_dist) radius = center_dist - arc_center theta = arcsin(line_dist * sqrt(2) / (2 * radius)) * 180 / pi if line_dist > center_dist: theta = -theta height = center_dist - line_dist / sqrt(2) max_dist = max(line_dist, center_dist) plt.plot([0, line_dist / sqrt(2)], [0, line_dist / sqrt(2)], color="black") plt.plot([0, -line_dist / sqrt(2)], [0, line_dist / sqrt(2)], color="black") plt.plot([-line_dist / sqrt(2), line_dist / sqrt(2)], [max_dist + 10, max_dist + 10], color="white") base_size = 3 #first base plt.plot([90 / sqrt(2), 90 / sqrt(2) - base_size], [90 / sqrt(2), 90 / sqrt(2) + base_size], color='black') plt.plot([90 / sqrt(2), 90 / sqrt(2) - base_size], [90 / sqrt(2) + base_size * 2, 90 / sqrt(2) + base_size], color='black') plt.plot([90 / sqrt(2), 90 / sqrt(2) + base_size], [90 / sqrt(2) + base_size * 2, 90 / sqrt(2) + base_size], color='black') #second base plt.plot([0, -base_size], [90 * sqrt(2), 90 * sqrt(2) + base_size], color='black') plt.plot([0, -base_size], [90 * sqrt(2) + base_size * 2, 90 * sqrt(2) + base_size], color='black') plt.plot([0, base_size], [90 * sqrt(2) + base_size * 2, 90 * sqrt(2) + base_size], color='black') plt.plot([0, base_size], [90 * sqrt(2), 90 * sqrt(2) + base_size], color='black') #third base plt.plot([-90 / sqrt(2), -(90 / sqrt(2) - base_size)], [90 / sqrt(2), 90 / sqrt(2) + base_size], color='black') plt.plot([-90 / sqrt(2), -(90 / sqrt(2) - base_size)], [90 / sqrt(2) + base_size * 2, 90 / sqrt(2) + base_size], color='black') plt.plot([-90 / sqrt(2), -(90 / sqrt(2) + base_size)], [90 / sqrt(2) + base_size * 2, 90 / sqrt(2) + base_size], color='black') fence = Arc((0, arc_center), height=2 * radius, width=2 * radius, angle=0, theta1=90 - theta, theta2=90 + theta, color="black") ax.add_patch(fence) infield = Arc((0, 0), height=320, width=150 * sqrt(2), angle=0, theta1=45, theta2=135, color="black") ax.add_patch(infield) mound = plt.Circle((0, 60.6), 10, color='black', fill=False) ax.add_patch(mound) for player in players: pos = plt.Circle(player, 5, color='blue') ax.add_patch(pos) for ball, color, size in zip(balls, ball_colors, ball_sizes): pos = plt.Circle(ball, size, color=color) ax.add_patch(pos) plt.title(title) plt.show()
def circos_plot(interaction_space, sender_cells, receiver_cells, ligands, receptors, excluded_score=0, metadata=None, sample_col='#SampleID', group_col='Groups', meta_cmap='Set2', cells_cmap='Pastel1', colors=None, ax=None, figsize=(10, 10), fontsize=14, legend=True, ligand_label_color='dimgray', receptor_label_color='dimgray', filename=None): '''Generates the circos plot in the exact order that sender and receiver cells are provided. Similarly, ligands and receptors are sorted by the order they are input. Parameters ---------- interaction_space : cell2cell.core.interaction_space.InteractionSpace Interaction space that contains all a distance matrix after running the the method compute_pairwise_communication_scores. Alternatively, this object can a SingleCellInteractions or a BulkInteractions object after running the method compute_pairwise_communication_scores. sender_cells : list List of cells to be included as senders. receiver_cells : list List of cells to be included as receivers. ligands : list List of genes/proteins to be included as ligands produced by the sender cells. receptors : list List of genes/proteins to be included as receptors produced by the receiver cells. excluded_score : float, default=0 Rows that have a communication score equal or lower to this will be dropped from the network. metadata : pandas.Dataframe, default=None Metadata associated with the cells, cell types or samples in the matrix containing CCC scores. If None, cells will be color only by individual cells. sample_col : str, default='#SampleID' Column in the metadata for the cells, cell types or samples in the matrix containing CCC scores. group_col : str, default='Groups' Column in the metadata containing the major groups of cells, cell types or samples in the matrix with CCC scores. meta_cmap : str, default='Set2' Name of the matplotlib color palette for coloring the major groups of cells. cells_cmap : str, default='Pastel1' Name of the color palette for coloring individual cells. colors : dict, default=None Dictionary containing tuples in the RGBA format for indicating colors of major groups of cells. If colors is specified, meta_cmap will be ignored. ax : matplotlib.axes.Axes, default=None Axes instance for a plot. figsize : tuple, default=(10, 10) Size of the figure (width*height), each in inches. fontsize : int, default=14 Font size for ligand and receptor labels. legend : boolean, default=True Whether including legends for cell and cell group colors as well as ligand/receptor colors. ligand_label_color : str, default='dimgray' Name of the matplotlib color palette for coloring the labels of ligands. receptor_label_color : str, default='dimgray' Name of the matplotlib color palette for coloring the labels of receptors. filename : str, default=None Path to save the figure of the elbow analysis. If None, the figure is not saved. Returns ------- ax : matplotlib.axes.Axes Axes instance containing a circos plot. ''' if hasattr(interaction_space, 'interaction_elements'): if 'communication_matrix' not in interaction_space.interaction_elements.keys( ): raise ValueError( 'Run the method compute_pairwise_communication_scores() before generating circos plots.' ) else: readable_ccc = get_readable_ccc_matrix( interaction_space.interaction_elements['communication_matrix']) elif hasattr(interaction_space, 'interaction_space'): if 'communication_matrix' not in interaction_space.interaction_space.interaction_elements.keys( ): raise ValueError( 'Run the method compute_pairwise_communication_scores() before generating circos plots.' ) else: readable_ccc = get_readable_ccc_matrix( interaction_space.interaction_space. interaction_elements['communication_matrix']) else: raise ValueError('Not a valid interaction_space') # Figure setups if ax is None: R = 1.0 center = (0, 0) fig = plt.figure(figsize=figsize, frameon=False) ax = fig.add_axes([0., 0., 1., 1.], aspect='equal') ax.set_axis_off() ax.set_xlim((-R * 1.05 + center[0]), (R * 1.05 + center[0])) ax.set_ylim((-R * 1.05 + center[1]), (R * 1.05 + center[1])) else: xlim = ax.get_xlim() ylim = ax.get_ylim() x_range = abs(xlim[1] - xlim[0]) y_range = abs(ylim[1] - ylim[0]) R = np.nanmin([x_range / 2.0, y_range / 2.0]) / 1.05 center = (np.nanmean(xlim), np.nanmean(ylim)) # Elements to build network # TODO: Add option to select sort_by: None (as input), cells, proteins or metadata sorted_nodes = sort_nodes(sender_cells=sender_cells, receiver_cells=receiver_cells, ligands=ligands, receptors=receptors) # Build network G = _build_network(sender_cells=sender_cells, receiver_cells=receiver_cells, ligands=ligands, receptors=receptors, sorted_nodes=sorted_nodes, readable_ccc=readable_ccc, excluded_score=excluded_score) # Get coordinates nodes_dict = get_arc_angles(G=G, sorting_feature='sorting') edges_dict = dict() for k, v in nodes_dict.items(): edges_dict[k] = get_cartesian(theta=np.nanmean(v), radius=0.95 * R / 2., center=center, angle='degrees') small_R = determine_small_radius(edges_dict) # Colors cells = list(set(sender_cells + receiver_cells)) if metadata is not None: meta = metadata.set_index(sample_col).reindex(cells) meta = meta[[group_col]].fillna('NA') labels = meta[group_col].unique().tolist() if colors is None: colors = get_colors_from_labels(labels, cmap=meta_cmap) meta['Color'] = [colors[idx] for idx in meta[group_col]] else: meta = pd.DataFrame(index=cells) # Colors for cells, not major groups colors = get_colors_from_labels(cells, cmap=cells_cmap) meta['Cells-Color'] = [colors[idx] for idx in meta.index] # signal_colors = {'ligand' : 'brown', 'receptor' : 'black'} signal_colors = { 'ligand': ligand_label_color, 'receptor': receptor_label_color } # Draw edges # TODO: Automatically determine lw given the size of the arcs (each ligand or receptor) lw = 10 for l, r in G.edges: path = Path([edges_dict[l], center, edges_dict[r]], [Path.MOVETO, Path.CURVE3, Path.CURVE3]) patch = patches.FancyArrowPatch( path=path, arrowstyle="->,head_length={},head_width={}".format( lw / 3.0, lw / 3.0), lw=lw / 2., edgecolor='gray', #meta.at[l.split('^')[0], 'Cells-Color'], zorder=1, facecolor='none', alpha=0.15) ax.add_patch(patch) # Draw nodes # TODO: Automatically determine lw given the size of the figure cell_legend = dict() if metadata is not None: meta_legend = dict() else: meta_legend = None for k, v in nodes_dict.items(): diff = 0.05 * abs( v[1] - v[0]) # Distance to substract and avoid nodes touching each others cell = k.split('^')[0] cell_color = meta.at[cell, 'Cells-Color'] cell_legend[cell] = cell_color ax.add_patch( Arc(center, R, R, theta1=diff + v[0], theta2=v[1] - diff, edgecolor=cell_color, lw=lw)) coeff = 1.0 if metadata is not None: coeff = 1.1 meta_color = meta.at[cell, 'Color'] ax.add_patch( Arc(center, coeff * R, coeff * R, theta1=diff + v[0], theta2=v[1] - diff, edgecolor=meta_color, lw=10)) meta_legend[meta.at[cell, group_col]] = meta_color label_coord = get_cartesian(theta=np.nanmean(v), radius=coeff * R / 2. + min([small_R * 3, coeff * R * 0.05]), center=center, angle='degrees') # Add Labels v2 = label_coord x = v2[0] y = v2[1] rotation = np.nanmean(v) if x >= 0: ha = 'left' else: ha = 'right' va = 'center' if (rotation <= 90): rotation = abs(rotation) elif (rotation <= 180): rotation = -abs(rotation - 180) elif (rotation <= 270): rotation = abs(rotation - 180) else: rotation = abs(rotation) ax.text(x, y, k.split('^')[1], rotation=rotation, rotation_mode="anchor", horizontalalignment=ha, verticalalignment=va, color=signal_colors[G.nodes[k]['signal']], fontsize=fontsize) # Draw legend if legend: generate_circos_legend(cell_legend=cell_legend, meta_legend=meta_legend, signal_legend=signal_colors, fontsize=fontsize) if filename is not None: plt.savefig(filename, dpi=300, bbox_inches='tight') return ax
import matplotlib.pyplot as plt from matplotlib.patches import Arc m = [0, -0.5] n = [-0.5, 0] R = 1.0 x, y = 0.0, 0.0 a, b = R, R fig_width, fig_height = 1, 1 fig = plt.figure(figsize=(fig_width, fig_height), frameon=False) ax = fig.add_axes([0.0, 0.0, 1.0, 1.0], aspect='equal') ax.set_xlim(-R, R) ax.set_ylim(-R, R) ax.axhline(0.0) ax.axvline(0.0) print("give the theta1") z = float(input()) ax.add_patch(Arc((x, y), a, b, theta1=0.0, theta2=360.0, edgecolor='w')) print("give the theta2") p = float(input()) q = z r = p ax.add_patch(Arc((x, y), a, b, theta1=q, theta2=r, edgecolor='b', lw=1.5)) plt.plot(x, y, m, n) plt.show()
def draw_ball_field(color='#20458C', lw=2): """ 绘制篮球场 """ # 新建一个大小为(6,6)的绘图窗口 plt.figure(figsize=(6, 6)) # 获得当前的Axes对象ax,进行绘图 ax = plt.gca() # 对篮球场进行底色填充 lines_outer_rec = Rectangle(xy=(-250, -47.5), width=500, height=470, linewidth=lw, color='#F0F0F0', fill=True) # 设置篮球场填充图层为最底层 lines_outer_rec.set_zorder(0) # 将rec添加进ax ax.add_patch(lines_outer_rec) # 绘制篮筐,半径为7.5 circle_ball = Circle(xy=(0, 0), radius=7.5, linewidth=lw, color=color, fill=False) # 将circle添加进ax ax.add_patch(circle_ball) # 绘制篮板,尺寸为(60,1) plate = Rectangle(xy=(-30, -7.5), width=60, height=-1, linewidth=lw, color=color, fill=False) # 将rec添加进ax ax.add_patch(plate) # 绘制2分区的外框线,尺寸为(160,190) outer_rec = Rectangle(xy=(-80, -47.5), width=160, height=190, linewidth=lw, color=color, fill=False) # 将rec添加进ax ax.add_patch(outer_rec) # 绘制2分区的内框线,尺寸为(120,190) inner_rec = Rectangle(xy=(-60, -47.5), width=120, height=190, linewidth=lw, color=color, fill=False) # 将rec添加进ax ax.add_patch(inner_rec) # 绘制罚球区域圆圈,半径为60 circle_punish = Circle(xy=(0, 142.5), radius=60, linewidth=lw, color=color, fill=False) # 将circle添加进ax ax.add_patch(circle_punish) # 绘制三分线的左边线 three_left_rec = Rectangle(xy=(-220, -47.5), width=0, height=140, linewidth=lw, color=color, fill=False) # 将rec添加进ax ax.add_patch(three_left_rec) # 绘制三分线的右边线 three_right_rec = Rectangle(xy=(220, -47.5), width=0, height=140, linewidth=lw, color=color, fill=False) # 将rec添加进ax ax.add_patch(three_right_rec) # 绘制三分线的圆弧,圆心为(0,0),半径为238.66,起始角度为22.8,结束角度为157.2 three_arc = Arc(xy=(0, 0), width=477.32, height=477.32, theta1=22.8, theta2=157.2, linewidth=lw, color=color, fill=False) # 将arc添加进ax ax.add_patch(three_arc) # 绘制中场处的外半圆,半径为60 center_outer_arc = Arc(xy=(0, 422.5), width=120, height=120, theta1=180, theta2=0, linewidth=lw, color=color, fill=False) # 将arc添加进ax ax.add_patch(center_outer_arc) # 绘制中场处的内半圆,半径为20 center_inner_arc = Arc(xy=(0, 422.5), width=40, height=40, theta1=180, theta2=0, linewidth=lw, color=color, fill=False) # 将arc添加进ax ax.add_patch(center_inner_arc) # 绘制篮球场外框线,尺寸为(500,470) lines_outer_rec = Rectangle(xy=(-250, -47.5), width=500, height=470, linewidth=lw, color=color, fill=False) # 将rec添加进ax ax.add_patch(lines_outer_rec) return ax
arrowprops=dict(arrowstyle='->, head_length=0.8, head_width=0.5')) plt.text(xhat - 0.17, yhat + 0.21, r'$F(u)$', fontsize=fsize) plt.plot(xhat, yc + 0.06, 'ko', ms=8.0, mfc='w') plt.text(xhat + 0.05, yc + 0.05, '$\it{unconstrained}\,\, \it{minimizer}$', fontsize=12.0) ax = plt.gca() for r in [0.4, 0.5, 0.6, 0.7]: alpha = (180.0 / np.pi) * np.arcsin(0.3 / r) beta = 90.0 + (180.0 / np.pi) * np.arcsin(0.25 / r) beta = min(beta, 180.0 - alpha) arc = Arc((xhat, yc), 2.0 * r, 2.0 * r, angle=0.0, theta1=alpha, theta2=beta, color='k', lw=0.75) ax.add_patch(arc) plt.text(-0.2, 0.7, r'$\mathcal{H}$', fontsize=fsize) plt.text(0.9, 0.6, r'$\mathcal{K}_\varphi$', fontsize=fsize) plt.axis('tight') plt.axis('off') plt.axis('equal') writeout('cartoonplane.pdf') # inner cone approx figure plt.figure(figsize=(8, 6)) xm, ym = 0.6, 0.4 makeaxes(-0.4, xm, -0.25, ym)
def draw_court(ax=None, color='gray', lw=1, outer_lines=False): """ Returns an axes with a basketball court drawn onto to it. Function taken from tutorial by Savvas Tjortjoglou This function draws a court based on the x and y-axis values that the NBA stats API provides for the shot chart data. For example, the NBA stat API represents the center of the hoop at the (0,0) coordinate. Twenty-two feet from the left of the center of the hoop in is represented by the (-220,0) coordinates. So one foot equals +/-10 units on the x and y-axis. TODO: explain the parameters """ if ax is None: ax = plt.gca() # Create the various parts of an NBA basketball court # Create the basketball hoop hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False) # Create backboard backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color) # The paint # Create the outer box 0f the paint, width=16ft, height=19ft outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color, fill=False) # Create the inner box of the paint, widt=12ft, height=19ft inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color, fill=False) # Create free throw top arc top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180, linewidth=lw, color=color, fill=False) # Create free throw bottom arc bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color, linestyle='dashed') # Restricted Zone, it is an arc with 4ft radius from center of the hoop restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw, color=color) # Three point line # Create the right side 3pt lines, it's 14ft long before it arcs corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=lw, color=color) # Create the right side 3pt lines, it's 14ft long before it arcs corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=lw, color=color) # 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw, color=color) # Center Court center_outer_arc = Arc((0, 422.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color) center_inner_arc = Arc((0, 422.5), 40, 40, theta1=180, theta2=0, linewidth=lw, color=color) # List of the court elements to be plotted onto the axes court_elements = [ hoop, backboard, outer_box, inner_box, top_free_throw, bottom_free_throw, restricted, corner_three_a, corner_three_b, three_arc, center_outer_arc, center_inner_arc ] if outer_lines: # Draw the half court line, baseline and side out bound lines outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw, color=color, fill=False) court_elements.append(outer_lines) # Add the court elements onto the axes for element in court_elements: ax.add_patch(element) return ax
def draw_court(ax=None, color='black', outer_lines=False): outer_lw = 4 inner_lw = 4 # If an axes object isn't provided to plot onto, just get current one if ax is None: ax = plt.gca() # Create the various parts of an NBA basketball court # Create the basketball hoop # Diameter of a hoop is 18" so it has a radius of 9", which is a value # 7.5 in our coordinate system hoop = Circle((0, 0), radius=7.5, linewidth=inner_lw, color=color, fill=False, zorder=25) # Create backboard backboard = Rectangle((-30, -7.5), 60, -1, linewidth=inner_lw, color=color, zorder=0) # The paint # Create the outer box 0f the paint, width=16ft, height=19ft left_paint = Rectangle((-80, -47.5), 0, 190, linewidth=inner_lw, color=color, fill=False, zorder=0) # Create the outer box 0f the paint, width=16ft, height=19ft right_paint = Rectangle((80, 142.5), 0, -190, linewidth=inner_lw, color=color, fill=False, zorder=0) # Create the outer box 0f the paint, width=16ft, height=19ft free_throw_line = Rectangle((-80, 142.5), 160, 0, linewidth=inner_lw, color=color, fill=False, zorder=0) # Create free throw top arc top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180, linewidth=inner_lw, color=color, fill=False, zorder=0) # Restricted Zone, it is an arc with 4ft radius from center of the hoop restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=inner_lw, color=color, zorder=0) # Three point line # Create the side 3pt lines, they are 14ft long before they begin to arc corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=inner_lw, color=color, zorder=0) corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=inner_lw, color=color) # 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop # I just played around with the theta values until they lined up with the # threes three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=inner_lw, color=color, zorder=0) # List of the court elements to be plotted onto the axes court_elements = [ hoop, backboard, left_paint, right_paint, free_throw_line, top_free_throw, corner_three_a, corner_three_b, three_arc, restricted ] if outer_lines: # Draw the half court line, baseline and side out bound lines outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=outer_lw, color=color, fill=False, zorder=0) court_elements.append(outer_lines) # Add the court elements onto the axes for element in court_elements: ax.add_patch(element) return ax
# give it a big marker ax1.plot([x], [y], marker='x', linestyle='None', mfc='red', mec='red', markersize=10) ################################################## # make the axes ax = subplot(312, aspect='equal', sharex=ax1, sharey=ax1) ax.set_aspect('equal', 'datalim') # make the lower-bound arc diam = (r - delta) * 2.0 lower_arc = Arc((0.0, 0.0), diam, diam, 0.0, fill=False, edgecolor="darkgreen") ax.add_patch(lower_arc) # make the target arc diam = r * 2.0 target_arc = Arc((0.0, 0.0), diam, diam, 0.0, fill=False, edgecolor="darkred") ax.add_patch(target_arc) # make the upper-bound arc diam = (r + delta) * 2.0 upper_arc = Arc((0.0, 0.0), diam, diam, 0.0, fill=False, edgecolor="darkblue") ax.add_patch(upper_arc) # make the target diam = delta * 2.0 target = Arc((x, y), diam, diam, 0.0, fill=False, edgecolor="#DD1208")
def draw(self, ax, showframe=False): """ Draw the element ax : matplotlib axis showframe : Draw the axis frame. Useful for debugging. """ for path in self.paths: ax.plot(path[:, 0], path[:, 1], color=self.color, lw=self.lw, solid_capstyle='round', ls=self.ls) for s in self.shapes: if s.get('shape') == 'circle': xy = np.array(s.get('center', [0, 0])) xy = self.translate(xy - self.ofst) rad = s.get('radius', 1) * self.z fill = s.get('fill', False) fillcolor = s.get('fillcolor', self.color) circ = plt.Circle(xy=xy, radius=rad, ec=self.color, fc=fillcolor, fill=fill, zorder=3, lw=self.lw) ax.add_patch(circ) elif s.get('shape') == 'poly': xy = np.array(s.get('xy', [[0, 0]])) xy = self.translate(xy - self.ofst) closed = s.get('closed', True) fill = s.get('fill', False) fillcolor = s.get('fillcolor', self.color) poly = plt.Polygon(xy=xy, closed=closed, ec=self.color, fc=fillcolor, fill=fill, zorder=3, lw=self.lw) ax.add_patch(poly) elif s.get('shape') == 'arc': xy = np.array(s.get('center', [0, 0])) xy = self.translate(xy - self.ofst) w = s.get('width', 1) * self.z h = s.get('height', 1) * self.z th1 = s.get('theta1', 35) th2 = s.get('theta2', -35) if self.reverse: th1, th2 = th2, th1 angle = s.get('angle', self.theta) arc = Arc(xy, width=w, height=h, theta1=th1, theta2=th2, angle=angle, color=self.color, lw=self.lw) ax.add_patch(arc) # Add an arrowhead to the arc arrow = s.get('arrow', None) # 'cw' or 'ccw' or None if arrow is not None: if arrow == 'ccw': dx = np.cos(np.deg2rad(th2 + 90)) / 100 dy = np.sin(np.deg2rad(th2 + 90)) / 100 s = [ xy[0] + w / 2 * np.cos(np.deg2rad(th2)), xy[1] + h / 2 * np.sin(np.deg2rad(th2)) ] else: dx = -np.cos(np.deg2rad(th1 + 90)) / 100 dy = -np.sin(np.deg2rad(th1 + 90)) / 100 s = [ xy[0] + w / 2 * np.cos(np.deg2rad(th1)), xy[1] + h / 2 * np.sin(np.deg2rad(th1)) ] # Rotate the arrow head co = np.cos(np.radians(angle)) so = np.sin(np.radians(angle)) m = np.array([[co, so], [-so, co]]) s = np.dot(s - xy, m) + xy darrow = np.dot([dx, dy], m) ax.arrow(s[0], s[1], darrow[0], darrow[1], head_width=.15, head_length=.25, color=self.color) elif s.get('shape') == 'arrow': start = np.array(s.get('start', [0, 0])) end = np.array(s.get('end', [1, 0])) start = self.translate(start - self.ofst) end = self.translate(end - self.ofst) hw = s.get('headwidth', .1) hl = s.get('headlength', .2) ax.arrow(start[0], start[1], end[0] - start[0], end[1] - start[1], head_width=hw, head_length=hl, length_includes_head=True, color=self.color, lw=self.lw) for label, loc, align, size in self.strs: loc = self.translate(np.array(loc)) ha = align[0] va = align[1] ax.text(loc[0], loc[1], label, transform=ax.transData, horizontalalignment=ha, verticalalignment=va, fontsize=size)
def plot_loads_old(model, load_group, title, save_plot=False): """ Takes the structure and load dictionary. Displays the structure with the user defined loads TO DO: display of forced rotations """ # Settings # ------------------------------------ forceColor = 'red' displacementColor = 'green' MomentColor = 'blue' # ------------------------------------ try: nodalLoads = model['Loads'][load_group]['Nodal'] except: nodalLoads = [] try: pointLoads = model['Loads'][load_group]['Point'] except: pointLoads = [] try: lineLoads = model['Loads'][load_group]['Distributed'] except: lineLoads = [] try: functionLoads = model['Loads'][load_group]['Functions'] except: functionLoads = [] try: displacements = model['Loads'][load_group]['Initial Displacements'] except: displacements = [] elements = model['Beams']['Nodes'] nodes = model['Nodes']['Location'] # Determine Scaling Factors # ------------------------------------ x_min = min([node[0] for node in nodes]) x_max = max([node[0] for node in nodes]) z_min = min([node[1] for node in nodes]) z_max = max([node[1] for node in nodes]) length = (((x_max - x_min)**2 + (z_max - z_min)**2)**0.5) scaleDisplacements = 20 max_nodal = max([ max(abs(nodalload[1]), abs(nodalload[2])) for nodalload in nodalLoads ] + [0]) max_point = max([ max(abs(pointload[2]), abs(pointload[3])) for pointload in pointLoads ] + [0]) max_force = max(max_point, max_nodal, 0.0001) max_length = length / 18 min_length = length / 100 max_distributed = max([ max(abs(lineload[3]), abs(lineload[6]), abs(lineload[4]), abs(lineload[7]), abs(lineload[5]), abs(lineload[8])) for lineload in lineLoads ] + [0]) values_functions = [] for functionload in functionLoads: for i in range(3): if functionload[3 + i] != 0 and functionload[3 + i] != None: values_functions.extend([ abs(functionload[3 + i](x)) for x in np.linspace( functionload[1], functionload[2], num=15) ]) max_functional = max(values_functions + [0]) scaleDistributedForces = length / 8 / max(max_distributed, max_functional, 0.0001) # ------------------------------------ # Set up the plot fig, ax = initialize_plot() plotTitle(fig, 'Structure and Loads') plotStructure(model, ax) showOrientation(model, ax) plot_supports(model, ax) # if 'Releases' in model['Beams']: # plotHinges(model, ax) # Add identifiers for legend ax.plot( 0, 0, color=displacementColor, label=f'Forced Displacement (scaled by factor {scaleDisplacements})') ax.plot(0, 0, color=forceColor, label='Force') ax.plot(0, 0, color=MomentColor, label='Moment') # Cycle through nodal Forces for i in range(len(nodalLoads)): Fx = np.sign(nodalLoads[i][1]) * max( abs(nodalLoads[i][1]) / max_force * max_length, min_length) Fy = np.sign(nodalLoads[i][2]) * max( abs(nodalLoads[i][2]) / max_force * max_length, min_length) Mz = nodalLoads[i][3] if (abs(Fx) + abs(Fy)) > 0: targetX = nodes[nodalLoads[i][0]][0] targetY = nodes[nodalLoads[i][0]][1] arrow = FancyArrow(targetX, targetY, Fx, Fy, length_includes_head=True, head_width=3, linewidth=2, color=forceColor, zorder=10) ax.add_patch(arrow) if Mz != 0: targetX = nodes[nodalLoads[i][0]][0] targetY = nodes[nodalLoads[i][0]][1] # ax.plot(targetX,targetY, marker='o', markersize=4, alpha=1, color=MomentColor) if Mz > 0: arc = Arc([targetX, targetY], 1, 1, 0, 240, 110, linewidth=2, color=MomentColor, zorder=5) ax.add_patch(arc) arrow = FancyArrow(targetX - 0.35255, targetY + 0.35405, -0.01, -0.005, length_includes_head=True, head_width=3, linewidth=0.5, color=MomentColor, zorder=5) else: arc = Arc([targetX, targetY], 1, 1, 0, 70, 300, linewidth=2, color=MomentColor, zorder=5) ax.add_patch(arc) arrow = FancyArrow(targetX + 0.35255, targetY + 0.35405, +0.01, -0.005, length_includes_head=True, head_width=3, linewidth=0.5, color=MomentColor, zorder=5) ax.add_patch(arrow) # Cycle through elements for i in range(len(elements)): elementVector = [ nodes[elements[i][1]][0] - nodes[elements[i][0]][0], nodes[elements[i][1]][1] - nodes[elements[i][0]][1] ] elementVector = elementVector / np.linalg.norm(elementVector) # Plot point loads for j in range(len(pointLoads)): if int(pointLoads[j][0]) == i: loc = pointLoads[j][1] Fx = pointLoads[j][2] * scaleForces Fy = pointLoads[j][3] * scaleForces Mz = pointLoads[j][4] # Prevent error of arrow without length if (abs(Fx) + abs(Fy)) > 0: targetX = nodes[elements[i][0]][0] + elementVector[0] * loc targetY = nodes[elements[i][0]][1] + elementVector[1] * loc arrow = FancyArrow(targetX - Fx, targetY - Fy, Fx, Fy, length_includes_head=True, head_width=4, linewidth=2, color=forceColor, zorder=10) ax.add_patch(arrow) if Mz != 0: targetX = nodes[elements[i][0]][0] + elementVector[0] * loc targetY = nodes[elements[i][0]][1] + elementVector[1] * loc ax.plot(targetX, targetY, marker='o', markersize=4, alpha=1, color=MomentColor) if Mz > 0: arc = Arc([targetX, targetY], 1, 1, 0, 240, 110, linewidth=2, color=MomentColor, zorder=5) ax.add_patch(arc) arrow = FancyArrow(targetX - 0.35255, targetY + 0.35405, -0.01, -0.005, length_includes_head=True, head_width=0.2, linewidth=0.5, color=MomentColor, zorder=5) else: arc = Arc([targetX, targetY], 1, 1, 0, 70, 300, linewidth=2, color=MomentColor, zorder=5) ax.add_patch(arc) arrow = FancyArrow(targetX + 0.35255, targetY + 0.35405, +0.01, -0.005, length_includes_head=True, head_width=0.2, linewidth=0.5, color=MomentColor, zorder=5) ax.add_patch(arrow) # Plot line loads for j in range(len(lineLoads)): if int(lineLoads[j][0]) == i: lStart = lineLoads[j][1] lEnd = lineLoads[j][2] qxStart = lineLoads[j][3] * scaleDistributedForces qyStart = lineLoads[j][4] * scaleDistributedForces mzStart = lineLoads[j][5] * scaleDistributedForces qxEnd = lineLoads[j][6] * scaleDistributedForces qyEnd = lineLoads[j][7] * scaleDistributedForces mzEnd = lineLoads[j][8] * scaleDistributedForces if qxStart != 0 or qyStart != 0 or qxEnd != 0 or qyEnd != 0: targetXStart = nodes[elements[i] [0]][0] + elementVector[0] * lStart targetXEnd = nodes[elements[i] [0]][0] + elementVector[0] * lEnd targetYStart = nodes[elements[i] [0]][1] + elementVector[1] * lStart targetYEnd = nodes[elements[i] [0]][1] + elementVector[1] * lEnd x = [targetXEnd - qxEnd, targetXStart - qxStart] y = [targetYEnd - qyEnd, targetYStart - qyStart] ax.plot(x, y, color=forceColor, linewidth=1.3) # draw Arrows amount = int((lEnd - lStart) / (length / 20) + 2) for k in range(amount): l = lStart + (lEnd - lStart) * k / (amount - 1) x = nodes[elements[i][0]][0] + elementVector[0] * l y = nodes[elements[i][0]][1] + elementVector[1] * l arrowlengthx = (lEnd - l) / ( lEnd - lStart) * qxStart + (l - lStart) / ( lEnd - lStart) * qxEnd arrowlengthy = (lEnd - l) / ( lEnd - lStart) * qyStart + (l - lStart) / ( lEnd - lStart) * qyEnd if abs(arrowlengthx) > length / 100 or abs( arrowlengthy) > length / 100: arrow = FancyArrow(x - arrowlengthx, y - arrowlengthy, arrowlengthx, arrowlengthy, length_includes_head=True, head_width=4, linewidth=1, color=forceColor, zorder=5) ax.add_patch(arrow) if mzStart != 0 or mzEnd != 0: targetXStart = nodes[elements[i] [0]][0] + elementVector[0] * lStart targetXEnd = nodes[elements[i] [0]][0] + elementVector[0] * lEnd targetYStart = nodes[elements[i] [0]][1] + elementVector[1] * lStart targetYEnd = nodes[elements[i] [0]][1] + elementVector[1] * lEnd x = [ targetXEnd - elementVector[1] * mzEnd, targetXStart - elementVector[1] * mzStart ] y = [ targetYEnd + elementVector[0] * mzEnd, targetYStart + elementVector[0] * mzStart ] ax.plot(x, y, color=MomentColor, lineWidth=1.3) # draw Lines amount = int((lEnd - lStart) / (length / 20) + 2) for k in range(amount): l = lStart + (lEnd - lStart) * k / (amount - 1) x = nodes[elements[i][0]][0] + elementVector[0] * l y = nodes[elements[i][0]][1] + elementVector[1] * l arrowlengthx = -elementVector[1] * ( (lEnd - l) / (lEnd - lStart) * mzStart + (l - lStart) / (lEnd - lStart) * mzEnd) arrowlengthy = elementVector[0] * ( (lEnd - l) / (lEnd - lStart) * mzStart + (l - lStart) / (lEnd - lStart) * mzEnd) if abs(arrowlengthx) > length / 100 or abs( arrowlengthy) > length / 100: ax.plot([x, x + arrowlengthx], [y, y + arrowlengthy], color=MomentColor, lineWidth=1) # Plot forced displacements for j in range(len(displacements)): if int(displacements[j][0]) == i: if (abs(displacements[j][1] + abs(displacements[j][2]) > 0)): arrow = FancyArrow( nodes[int(displacements[j][0])][0], nodes[int(displacements[j][0])][1], scaleDisplacements * displacements[j][1], scaleDisplacements * displacements[j][2], length_includes_head=True, head_width=0.2, linewidth=2, color=displacementColor) ax.add_patch(arrow) if displacements[j][3] != 0: targetX = nodes[displacements[i][0]][0] targetY = nodes[displacements[i][0]][1] ax.plot(targetX, targetY, marker='o', markersize=4, alpha=1, color=displacementColor) arc = Arc([targetX, targetY], 1, 1, 0, 240, 120, linewidth=2, color=displacementColor, zorder=5) ax.add_patch(arc) if displacements[j][3] > 0: arrow = FancyArrow(targetX - 0.35255, targetY + 0.35405, -0.01, -0.005, length_includes_head=True, head_width=0.2, linewidth=0.5, color=displacementColor, zorder=5) else: arrow = FancyArrow(targetX - 0.35255, targetY - 0.35405, -0.01, +0.005, length_includes_head=True, head_width=0.2, linewidth=0.5, color=displacementColor, zorder=5) ax.add_patch(arrow) for j in range(len(functionLoads)): if int(functionLoads[j][0]) == i: lStart = functionLoads[j][1] lEnd = functionLoads[j][2] qx = functionLoads[j][3] qy = functionLoads[j][4] mz = functionLoads[j][5] if (qx != 0 and qx != None) or (qy != 0 and qy != None): targetXStart = nodes[elements[i] [0]][0] + elementVector[0] * lStart targetXEnd = nodes[elements[i] [0]][0] + elementVector[0] * lEnd targetYStart = nodes[elements[i] [0]][1] + elementVector[1] * lStart targetYEnd = nodes[elements[i] [0]][1] + elementVector[1] * lEnd x1 = [] y1 = [] # draw Arrows amount = int((lEnd - lStart) / (length / 20) + 2) for k in range(amount * 4 - 3): l = lStart + (lEnd - lStart) * k / (( (4 * amount - 3)) - 1) x = nodes[elements[i][0]][0] + elementVector[0] * l y = nodes[elements[i][0]][1] + elementVector[1] * l arrowlengthx = 0 arrowlengthy = 0 if (qx != 0 and qx != None): arrowlengthx += qx(l) * scaleDistributedForces if (qy != 0 and qy != None): arrowlengthy += qy(l) * scaleDistributedForces if ((abs(arrowlengthx) > length / 100 or abs(arrowlengthy) > length / 100) and k % 4 == 0): arrow = FancyArrow(x - arrowlengthx, y - arrowlengthy, arrowlengthx, arrowlengthy, length_includes_head=True, head_width=0.13, linewidth=1, color=forceColor, zorder=5) ax.add_patch(arrow) x1.append(x - arrowlengthx) y1.append(y - arrowlengthy) ax.plot(x1, y1, color=forceColor, lineWidth=1.3) if (mz != 0 and mz != None): targetXStart = nodes[elements[i] [0]][0] + elementVector[0] * lStart targetXEnd = nodes[elements[i] [0]][0] + elementVector[0] * lEnd targetYStart = nodes[elements[i] [0]][1] + elementVector[1] * lStart targetYEnd = nodes[elements[i] [0]][1] + elementVector[1] * lEnd x1 = [] y1 = [] # draw Lines amount = int((lEnd - lStart) / (length / 20) + 2) for k in range(amount * 4 - 3): l = lStart + (lEnd - lStart) * k / (( (4 * amount - 3)) - 1) x = nodes[elements[i][0]][0] + elementVector[0] * l y = nodes[elements[i][0]][1] + elementVector[1] * l arrowlengthx = -elementVector[1] * mz(l) arrowlengthy = elementVector[0] * mz(l) if ((abs(arrowlengthx) > length / 100 or abs(arrowlengthy) > length / 100) and k % 4 == 0): ax.plot([x, x + arrowlengthx], [y, y + arrowlengthy], color=MomentColor, lineWidth=1) x1.append(x + arrowlengthx) y1.append(y + arrowlengthy) ax.plot(x1, y1, color=MomentColor, lineWidth=1.3) #plotLegend(ax) adjustPlot(ax) plt.show() if save_plot: fig.savefig(title + '.png') return ax
def create_ncaa_half_court(ax=None, court_color='white', lw=3, lines_color='black', lines_alpha=0.5, paint_fill='Green', paint_alpha=0.4): # combining two independent plots with matplotlib # ax = axes if ax is None: ax = plt.gca() # Center Circle # Circle(xy, radius, color, fill) center_circle = Circle((50 / 2, 94 / 2), 6, linewidth=lw, color=lines_color, lw=lw, fill=False, alpha=lines_alpha) #Basketball Hoop hoop = Circle((50 / 2, 5.25), 1.5 / 2, linewidth=lw, color=lines_color, lw=lw, fill=False, alpha=lines_alpha) # Paint - 18 Feet 10 inches which converts to 18.83333 feet # Rectangle(xy, width, height, linewidth, edgecolor, facecolor) paint = Rectangle(((50 / 2) - 6, 0), 12, 18.833333, fill=paint_fill, alpha=paint_alpha, lw=lw, edgecolor='Green') paint_boarder = Rectangle(((50 / 2) - 6, 0), 12, 18.833333, fill=False, alpha=lines_alpha, lw=lw, edgecolor=lines_color) arc = Arc((50 / 2, 18.833333), 12, 12, theta1=-0, theta2=180, color=lines_color, lw=lw, alpha=lines_alpha) # Add Patches ax.add_patch(paint) ax.add_patch(paint_boarder) ax.add_patch(center_circle) ax.add_patch(hoop) ax.add_patch(arc) block1 = Rectangle(((50 / 2) - 6 - 0.666, 7), 0.666, 1, fill=True, alpha=lines_alpha, lw=0, edgecolor=lines_color, facecolor=lines_color) block2 = Rectangle(((50 / 2) + 6, 7), 0.666, 1, fill=True, alpha=lines_alpha, lw=0, edgecolor=lines_color, facecolor=lines_color) # add a patch ax.add_patch(block1) ax.add_patch(block2) #lines on freethrow line l1 = Rectangle(((50 / 2) - 6 - 0.666, 11), 0.666, 0.166, fill=True, alpha=lines_alpha, lw=0, edgecolor=lines_color, facecolor=lines_color) l2 = Rectangle(((50 / 2) - 6 - 0.666, 14), 0.666, 0.166, fill=True, alpha=lines_alpha, lw=0, edgecolor=lines_color, facecolor=lines_color) l3 = Rectangle(((50 / 2) - 6 - 0.666, 17), 0.666, 0.166, fill=True, alpha=lines_alpha, lw=0, edgecolor=lines_color, facecolor=lines_color) l4 = Rectangle(((50 / 2) + 6, 11), 0.666, 0.166, fill=True, alpha=lines_alpha, lw=0, edgecolor=lines_color, facecolor=lines_color) l5 = Rectangle(((50 / 2) + 6, 14), 0.666, 0.166, fill=True, alpha=lines_alpha, lw=0, edgecolor=lines_color, facecolor=lines_color) l6 = Rectangle(((50 / 2) + 6, 17), 0.666, 0.166, fill=True, alpha=lines_alpha, lw=0, edgecolor=lines_color, facecolor=lines_color) ax.add_patch(l1) ax.add_patch(l2) ax.add_patch(l3) ax.add_patch(l4) ax.add_patch(l5) ax.add_patch(l6) # 3 Point Line !!! three_pt = Arc((50 / 2, 6.25), 44.291, 44.291, theta1=12, theta2=168, color=lines_color, lw=lw, alpha=lines_alpha) ax.plot((3.34, 3.34), (0, 11.20), color=lines_color, lw=lw, alpha=lines_alpha) ax.plot((50 - 3.34, 50 - 3.34), (0, 11.20), color=lines_color, lw=lw, alpha=lines_alpha) ax.add_patch(three_pt) inner_arc = Arc((50 / 2, 18.833333), 12, 12, theta1=180, theta2=0, color=lines_color, lw=lw, alpha=lines_alpha, ls='--') ax.add_patch(inner_arc) # Restricted Area Marker restricted_area = Arc((50 / 2, 6.25), 8, 8, theta1=0, theta2=180, color=lines_color, lw=lw, alpha=lines_alpha) ax.add_patch(restricted_area) # Backboard ax.plot(((50 / 2) - 3, (50 / 2) + 3), (4, 4), color=lines_color, lw=lw * 1.5, alpha=lines_alpha) ax.plot((50 / 2, 50 / 2), (4.3, 4), color=lines_color, lw=lw, alpha=lines_alpha) # Half Court Line ax.axhline(94 / 2, color=lines_color, lw=lw, alpha=lines_alpha) ax.set_xlim(0, 50) ax.set_ylim(0, 94 / 2 + 2) ax.set_facecolor(court_color) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlabel('') return ax
def draw_court(ax=None, color='black', lw=2, outer_lines=False): # 如果坐标轴对象不提供绘图,就创建一个 if ax is None: ax = plt.gca() # 创建 NBA 篮球场 # 绘制篮球框 # 直径18的篮球框 # 7.5在坐标中 hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False) # 绘制篮板 backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color) # The paint # 绘制矩形宽 16ft, 高 19ft outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color, fill=False) # 绘制里面的小矩形, widt=12ft, height=19ft inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color, fill=False) # 绘制罚球顶弧 top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180, linewidth=lw, color=color, fill=False) # 绘制罚球低弧 bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color, linestyle='dashed') # 限制区, 以篮筐为中心,半径为 4ft的弧 restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw, color=color) # 三分线 # 绘制三分线边线,长 14ft corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=lw, color=color) corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=lw, color=color) # 三分线弧度,以篮筐为中心,离篮筐23.9 three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw, color=color) # 球场中心 center_outer_arc = Arc((0, 422.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color) center_inner_arc = Arc((0, 422.5), 40, 40, theta1=180, theta2=0, linewidth=lw, color=color) # 将上面写的球场属性用列表在轴上画出来 court_elements = [ hoop, backboard, outer_box, inner_box, top_free_throw, bottom_free_throw, restricted, corner_three_a, corner_three_b, three_arc, center_outer_arc, center_inner_arc ] if outer_lines: # 画半场线,基础线以及边缘线 outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw, color=color, fill=False) court_elements.append(outer_lines) # 添加球场元素到坐标上 for element in court_elements: ax.add_patch(element) return ax
def draw(self, ax, showframe=False): """ Draw the element ax : matplotlib axis showframe : Draw the axis frame. Useful for debugging. """ if self.fill: for i in range(len(self.paths)): tlist = [(x,y) for x, y in self.paths[i]] # Need tuples for set hashing if len(tlist) != len(set(tlist)): # duplicate points, assume closed shape ax.fill(*list(zip(*self.paths[i])), color=self.fill, zorder=0) for path in self.paths: ax.plot(path[:, 0], path[:, 1], color=self.color, lw=self.lw, solid_capstyle='round', ls=self.ls) for s in self.shapes: if s.get('fill', False): fill = True fillcolor = s.get('fillcolor', self.color) else: fill = self.fill is not None fillcolor = self.fill if s.get('shape') == 'circle': xy = np.array(s.get('center', [0, 0])) xy = self.translate(xy - self.ofst) rad = s.get('radius', 1) * self.z circ = plt.Circle(xy=xy, radius=rad, ec=self.color, fc=fillcolor, fill=fill, zorder=0, lw=self.lw) ax.add_patch(circ) elif s.get('shape') == 'poly': xy = np.array(s.get('xy', [[0, 0]])) xy = self.translate(xy - self.ofst) closed = s.get('closed', True) poly = plt.Polygon(xy=xy, closed=closed, ec=self.color, fc=fillcolor, fill=fill, zorder=0, lw=self.lw) ax.add_patch(poly) elif s.get('shape') == 'arc': xy = np.array(s.get('center', [0, 0])) xy = self.translate(xy - self.ofst) w = s.get('width', 1) * self.z h = s.get('height', 1) * self.z th1 = s.get('theta1', 35) th2 = s.get('theta2', -35) if self.reverse: th1, th2 = th1+180, th2+180 angle = s.get('angle', self.theta) arc = Arc(xy, width=w, height=h, theta1=th1, theta2=th2, angle=angle, color=self.color, lw=self.lw) ax.add_patch(arc) # Add an arrowhead to the arc arrow = s.get('arrow', None) # 'cw' or 'ccw' or None if arrow is not None: # Apply stretch to theta to match MPL's arc # (See change https://github.com/matplotlib/matplotlib/pull/8047/files) x, y = np.cos(np.deg2rad(th2)), np.sin(np.deg2rad(th2)) th2 = np.rad2deg(np.arctan2((w/h)*y, x)) x, y = np.cos(np.deg2rad(th1)), np.sin(np.deg2rad(th1)) th1 = np.rad2deg(np.arctan2((w/h)*y, x)) if arrow == 'ccw': dx = np.cos(np.deg2rad(th2+90)) / 100 dy = np.sin(np.deg2rad(th2+90)) / 100 s = [xy[0] + w/2*np.cos(np.deg2rad(th2)), xy[1] + h/2*np.sin(np.deg2rad(th2))] else: dx = -np.cos(np.deg2rad(th1+90)) / 100 dy = - np.sin(np.deg2rad(th1+90)) / 100 s = [xy[0] + w/2*np.cos(np.deg2rad(th1)), xy[1] + h/2*np.sin(np.deg2rad(th1))] # Rotate the arrow head co = np.cos(np.radians(angle)) so = np.sin(np.radians(angle)) m = np.array([[co, so],[-so, co]]) s = np.dot(s-xy, m)+xy darrow = np.dot([dx, dy], m) ax.arrow(s[0], s[1], darrow[0], darrow[1], head_width=.15, head_length=.25, color=self.color) elif s.get('shape') == 'arrow': start = np.array(s.get('start', [0, 0])) end = np.array(s.get('end', [1, 0])) start = self.translate(start - self.ofst) end = self.translate(end - self.ofst) hw = s.get('headwidth', .1) hl = s.get('headlength', .2) ax.arrow(start[0], start[1], end[0]-start[0], end[1]-start[1], head_width=hw, head_length=hl, length_includes_head=True, color=self.color, lw=self.lw) for label, loc, align, size in self.strs: loc = self.translate(np.array(loc)) ha = align[0] va = align[1] ax.text(loc[0], loc[1], label, transform=ax.transData, horizontalalignment=ha, verticalalignment=va, fontsize=size)
def drawCourt(self, ax=None, color='black', lw=2, outerLines=False): if ax is None: ax = plt.gca() # ax.set_axis_bgcolor('#FAFAFA') hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False) backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color) outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color, fill=False) inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color, fill=False) top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180, linewidth=lw, color=color, fill=False) bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color, linestyle='dashed') restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw, color=color) corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=lw, color=color) corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=lw, color=color) three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw, color=color) center_outer_arc = Arc((0, 422.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color) center_inner_arc = Arc((0, 422.5), 40, 40, theta1=180, theta2=0, linewidth=lw, color=color) court_elements = [ hoop, backboard, outer_box, inner_box, top_free_throw, bottom_free_throw, restricted, corner_three_a, corner_three_b, three_arc, center_outer_arc, center_inner_arc ] if outerLines: outerLines = Rectangle((-250, -47.5), 500, 470, linewidth=lw, color=color, fill=False) court_elements.append(outerLines) for element in court_elements: ax.add_patch(element) return ax
def pitch(ax): # size of the pitch is 120, 80 #Create figure #Pitch Outline & Centre Line plt.plot([0, 0], [0, 80], color="black") plt.plot([0, 120], [80, 80], color="black") plt.plot([120, 120], [80, 0], color="black") plt.plot([120, 0], [0, 0], color="black") plt.plot([60, 60], [0, 80], color="black") #Left Penalty Area plt.plot([14.6, 14.6], [57.8, 22.2], color="black") plt.plot([0, 14.6], [57.8, 57.8], color="black") plt.plot([0, 14.6], [22.2, 22.2], color="black") #Right Penalty Area plt.plot([120, 105.4], [57.8, 57.8], color="black") plt.plot([105.4, 105.4], [57.8, 22.5], color="black") plt.plot([120, 105.4], [22.5, 22.5], color="black") #Left 6-yard Box plt.plot([0, 4.9], [48, 48], color="black") plt.plot([4.9, 4.9], [48, 32], color="black") plt.plot([0, 4.9], [32, 32], color="black") #Right 6-yard Box plt.plot([120, 115.1], [48, 48], color="black") plt.plot([115.1, 115.1], [48, 32], color="black") plt.plot([120, 115.1], [32, 32], color="black") #Prepare Circles centreCircle = plt.Circle((60, 40), 8.1, color="black", fill=False) centreSpot = plt.Circle((60, 40), 0.71, color="black") leftPenSpot = plt.Circle((9.7, 40), 0.71, color="black") rightPenSpot = plt.Circle((110.3, 40), 0.71, color="black") #Draw Circles ax.add_patch(centreCircle) ax.add_patch(centreSpot) ax.add_patch(leftPenSpot) ax.add_patch(rightPenSpot) #Prepare Arcs # arguments for arc # x, y coordinate of centerpoint of arc # width, height as arc might not be circle, but oval # angle: degree of rotation of the shape, anti-clockwise # theta1, theta2, start and end location of arc in degree leftArc = Arc((9.7, 40), height=16.2, width=16.2, angle=0, theta1=310, theta2=50, color="black") rightArc = Arc((110.3, 40), height=16.2, width=16.2, angle=0, theta1=130, theta2=230, color="black") #Draw Arcs ax.add_patch(leftArc) ax.add_patch(rightArc)
def create_court(ax=None, color='black', lw=4): ax = plt.gca(xlim=[30, -30], ylim=[-7, 43], xticks=[], yticks=[], aspect=1.0) hoop = Circle((0, 0), radius=0.75, linewidth=lw, color=color) backboard = Rectangle((-3, -0.75), 6, -0.1, linewidth=lw, color=color) outer_box = Rectangle((-8, -5.25), 16, 19, linewidth=lw, color=color, fill=False) inner_box = Rectangle((-6, -5.25), 12, 19, linewidth=lw, color=color, fill=False) top_free_throw = Arc((0, 13.75), 12, 12, theta1=0, theta2=180, linewidth=lw, color=color, fill=False) bottom_free_throw = Arc((0, 13.75), 12, 12, theta1=180, theta2=0, linewidth=lw, color=color, linestyle='dashed') restricted = Arc((0, 0), 8, 8, theta1=0, theta2=180, linewidth=lw, color=color) corner_three_a = Rectangle((-22, -5.25), 0, np.sqrt(23.75**2 - 22.0**2) + 5.25, linewidth=lw, color=color) corner_three_b = Rectangle((22, -5.25), 0, np.sqrt(23.75**2 - 22.0**2) + 5.25, linewidth=lw, color=color) three_arc = Arc((0, 0), 47.5, 47.5, theta1=np.arccos(22 / 23.75) * 180 / np.pi, theta2=180.0 - np.arccos(22 / 23.75) * 180 / np.pi, linewidth=lw, color=color) court_elements = [ hoop, backboard, outer_box, inner_box, top_free_throw, bottom_free_throw, restricted, corner_three_a, corner_three_b, three_arc ] ax.plot([-25, 25], [-5.25, -5.25], linewidth=lw, color=color) for element in court_elements: ax.add_patch(element) return ax
def court(ax=None, color='black', lw=4, outer_lines=False,direction='up',short_three=False): ''' Plots an NBA court outer_lines - accepts False or True. Plots the outer side lines of the court. direction - 'up' or 'down' depending on how you like to view the court Original function from http://savvastjortjoglou.com/ ''' # If an axes object isn't provided to plot onto, just get current one if ax is None: if direction=='up': ax = plt.gca(xlim = [-30,30],ylim = [43,-7],xticks=[],yticks=[],aspect=1.0) plt.text(22,44,'By: Doingthedishes',color='black',horizontalalignment='center',fontsize=20,fontweight='bold') elif direction=='down': ax = plt.gca(xlim = [30,-30],ylim = [-7,43],xticks=[],yticks=[],aspect=1.0) plt.text(-22,-7,'By: Doingthedishes',color='black',horizontalalignment='center',fontsize=20,fontweight='bold') else: ax = plt.gca() # Create the various parts of an NBA basketball court # Create the basketball hoop # Diameter of a hoop is 1.5 hoop = Circle((0, 0), radius=0.75, linewidth=lw/2, color=color, fill=False) # Create backboard backboard = Rectangle((-3, -0.75), 6, -0.1, linewidth=lw, color=color) # The paint # Create the outer box of the paint, width=16ft, height=19ft outer_box = Rectangle((-8, -5.25), 16, 19, linewidth=lw, color=color, fill=False) # Create the inner box of the paint, widt=12ft, height=19ft inner_box = Rectangle((-6, -5.25), 12, 19, linewidth=lw, color=color, fill=False) # Create free throw top arc top_free_throw = Arc((0, 13.75), 12, 12, theta1=0, theta2=180, linewidth=lw, color=color, fill=False) # Create free throw bottom arc bottom_free_throw = Arc((0, 13.75), 12, 12, theta1=180, theta2=0, linewidth=lw, color=color, linestyle='dashed') # Restricted Zone, it is an arc with 4ft radius from center of the hoop restricted = Arc((0, 0), 8, 8, theta1=0, theta2=180, linewidth=lw, color=color) # Three point line if not short_three: corner_three_a = Rectangle((-22, -5.25), 0, np.sqrt(23.75**2-22.0**2)+5.25, linewidth=lw, color=color) corner_three_b = Rectangle((22, -5.25), 0, np.sqrt(23.75**2-22.0**2)+5.25, linewidth=lw, color=color) # 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop three_arc = Arc((0, 0), 47.5, 47.5, theta1=np.arccos(22/23.75)*180/np.pi, theta2=180.0-np.arccos(22/23.75)*180/np.pi, linewidth=lw, color=color) else: corner_three_a = Rectangle((-22, -5.25), 0, 5.25, linewidth=lw, color=color) corner_three_b = Rectangle((22, -5.25), 0, 5.25, linewidth=lw, color=color) # 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop three_arc = Arc((0, 0), 44.0, 44.0, theta1=0, theta2=180, linewidth=lw, color=color) # List of the court elements to be plotted onto the axes court_elements = [hoop, backboard, outer_box, inner_box, top_free_throw, bottom_free_throw, restricted, corner_three_a, corner_three_b, three_arc] if outer_lines: # Draw the half court line, baseline and side out bound lines outer_lines = Rectangle((-25, -5.25), 50, 46.75, linewidth=lw, color=color, fill=False) center_outer_arc = Arc((0, 41.25), 12, 12, theta1=180, theta2=0, linewidth=lw, color=color) center_inner_arc = Arc((0, 41.25), 4, 4, theta1=180, theta2=0, linewidth=lw, color=color) court_elements = court_elements + [outer_lines,center_outer_arc,center_inner_arc] else: ax.plot([-25,25],[-5.25,-5.25],linewidth=lw,color=color) # Add the court elements onto the axes for element in court_elements: ax.add_patch(element) # ax.axis('off') return ax
plt.setp(line_func,color = "blue", linewidth = 2) plt.setp(line_y_f, color = "red", linewidth = 2) plt.show() from matplotlib.patches import Circle, Wedge, Ellipse, Arc, Rectangle #figure = wedge((4, 4), 2, -90, 90) figure = Wedge((4, 4), 2, -90, 90) figure = Rectangle((10, 12), 5, 8) #figure = Wedge((4, 4), 2, -90) figure = Arc((6, 6), 5, 3, 0, 200, 100) from matplotlib.patches import Path, PathPatch import matplotlib.pyplot as plt n = 8 # размер области m = 7 # размер области plt.xlim(0, n) plt.ylim(0,m) ax = plt.gca() # создать массив точек
def visualize_contour_for_synthetic_dataset(model, d_i, x_data, y_data, basis, with_LDS=False, epsilon=0.5, num_power_iter=5, save_filename='prob_cont'): linewidth = 10 range_x = numpy.arange(-2.0, 2.1, 0.05) A_inv = linalg.inv(numpy.dot(basis, basis.T)) train_x_org = numpy.dot(x_data, numpy.dot(basis.T, A_inv)) test_x_org = numpy.zeros((range_x.shape[0]**2, 2)) train_x_1_ind = numpy.where(y_data == 1)[0] train_x_0_ind = numpy.where(y_data == 0)[0] for i in xrange(range_x.shape[0]): for j in xrange(range_x.shape[0]): test_x_org[range_x.shape[0] * i + j, 0] = range_x[i] test_x_org[range_x.shape[0] * i + j, 1] = range_x[j] test_x = numpy.dot(test_x_org, basis) x = T.matrix() f_p_y_given_x = theano.function(inputs=[x], outputs=model.forward_test(x)) pred = f_p_y_given_x(numpy.asarray(test_x, 'float32'))[:, 1] Z = numpy.zeros((range_x.shape[0], range_x.shape[0])) for i in xrange(range_x.shape[0]): for j in xrange(range_x.shape[0]): Z[i, j] = pred[range_x.shape[0] * i + j] Y, X = numpy.meshgrid(range_x, range_x) fontsize = 20 rc = 'r' bc = 'b' if (d_i == 1): rescale = 1.0 #/numpy.sqrt(500) arc1 = Arc(xy=[0.5 * rescale, -0.25 * rescale], width=2.0 * rescale, height=2.0 * rescale, angle=0, theta1=270, theta2=180, linewidth=linewidth, alpha=0.15, color=rc) arc2 = Arc(xy=[-0.5 * rescale, +0.25 * rescale], width=2.0 * rescale, height=2.0 * rescale, angle=0, theta1=90, theta2=360, linewidth=linewidth, alpha=0.15, color=bc) fig = plt.gcf() fig.gca().add_artist(arc1) fig.gca().add_artist(arc2) plt.xticks(fontsize=fontsize) plt.yticks(fontsize=fontsize) else: rescale = 1.0 #/numpy.sqrt(500) circle1 = Circle((0, 0), 1.0 * rescale, color=rc, alpha=0.2, fill=False, linewidth=linewidth) circle2 = Circle((0, 0), 0.15 * rescale, color=bc, alpha=0.2, fill=False, linewidth=linewidth) fig = plt.gcf() fig.gca().add_artist(circle1) fig.gca().add_artist(circle2) plt.xticks(fontsize=fontsize) plt.yticks(fontsize=fontsize) levels = [0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95] cs = plt.contour(X * rescale, Y * rescale, Z, 7, cmap='bwr', vmin=0., vmax=1.0, linewidths=8., levels=levels) cbar = plt.colorbar(cs) cbar.ax.tick_params(labelsize=fontsize) plt.setp(cs.collections, linewidth=1.0) plt.contour(X * rescale, Y * rescale, Z, 1, cmap='binary', vmin=0, vmax=0.5, linewidths=2.0) plt.xlim([-2. * rescale, 2. * rescale]) plt.ylim([-2. * rescale, 2. * rescale]) plt.xticks([-2.0, -1.0, 0, 1, 2.0], fontsize=fontsize) plt.yticks([-2.0, -1.0, 0, 1, 2.0], fontsize=fontsize) plt.scatter(train_x_org[train_x_1_ind, 0] * rescale, train_x_org[train_x_1_ind, 1] * rescale, s=100, marker='o', c=rc, label='$y=1$') plt.scatter(train_x_org[train_x_0_ind, 0] * rescale, train_x_org[train_x_0_ind, 1] * rescale, s=100, marker='^', c=bc, label='$y=0$') if (with_LDS == True): x = T.matrix() f_LDS = theano.function(inputs=[], outputs=LDS_finite_diff( x=x, forward_func=model.forward_test, main_obj_type='CE', epsilon=epsilon, norm_constraint='L2', num_power_iter=num_power_iter), givens={x: x_data}) ave_LDS = numpy.mean([f_LDS().mean() for i in xrange(50)]) print ave_LDS plt.title('Average $\widetilde{\\rm LDS}=%.3f$' % round(ave_LDS, 3), fontsize=fontsize) make_sure_path_exists("./figure") plt.savefig('figure/' + save_filename, transparent=True)
def create_smith(): # Create the figure object fig = plt.figure(facecolor='white') # Add a single plot to the figure ax = fig.add_subplot(1, 1, 1, aspect='equal') # fig.add_axes([0.05, 0.05, 1.1, 1.1]) # ax = fig.axes[0] # Remove the figure boundaries ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) # Add Smith-chart impedance circles Circ_zero = plt.Circle((0, 0), radius=1.0, linestyle='solid', linewidth=2, color='black', fill=False) Circ_unity = plt.Circle((0.5, 0), radius=0.5, linestyle='solid', linewidth=1, color='grey', fill=False) Circ_imag_low = Arc((1, -1), 2, 2, angle=0.0, theta1=90.0, theta2=180.0, linestyle='solid', linewidth=1, color='grey', fill=False) Circ_imag_high = Arc((1, 1), 2, 2, angle=0.0, theta1=180.0, theta2=270.0, linestyle='solid', linewidth=1, color='grey', fill=False) Real_Line = Line2D((-1, 1), (0, 0), linestyle='solid', linewidth=1, color='grey') #ax.axhline(0,xmin=-1,xmax=1,linestyle='solid',linewidth=1,color='grey') ax.add_patch(Circ_imag_high) ax.add_patch(Circ_imag_low) ax.add_patch(Circ_unity) ax.add_patch(Circ_zero) ax.add_line(Real_Line) return fig
import matplotlib.pyplot as plt from matplotlib.patches import Arc, Ellipse, Rectangle, Wedge fig, ax = plt.subplots(subplot_kw={"aspect": "equal"}) # 底部阴影 shadow = Ellipse((2.5, 0.5), 4.2, 0.5, color="#888888", alpha=0.2) # 底座 ax.plot([1, 4], [1, 1.3], color="#000000") base = Arc((2.5, 1.1), 3, 1, angle=10, theta1=0, theta2=180, color="#000000", alpha=0.8) # 轮子 left_wheel = Ellipse((1, 1), 0.7, 0.4, angle=95, color="#000000") right_wheel = Ellipse((4, 1.3), 0.7, 0.4, angle=85, color="#000000") # 底部关节 bottom_join1 = Ellipse((2.5, 2), 1, 0.3, color="#888888", alpha=0.2) bottom_join2 = Ellipse((2.5, 1.7), 1, 0.3, color="#888888", alpha=0.2) # 肩膀关节 left_shoulder = Ellipse((1, 5.75), 0.5, 0.25, angle=90, color="#000000") right_shoulder = Ellipse((4, 5.75), 0.5, 0.25, angle=90, color="#000000")
def draw_court(ax=None, color='black', lw=2, outer_lines=False): '''Draws NBA court on axis. Source: http://savvastjortjoglou.com/nba-shot-sharts.html''' # If an axes object isn't provided to plot onto, just get current one if ax is None: ax = plt.gca() # Create the various parts of an NBA basketball court # Create the basketball hoop # Diameter of a hoop is 18" so it has a radius of 9", which is a value # 7.5 in our coordinate system hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False) # Create backboard backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color) # The paint # Create the outer box 0f the paint, width=16ft, height=19ft outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color, fill=False) # Create the inner box of the paint, widt=12ft, height=19ft inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color, fill=False) # Create free throw top arc top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180, linewidth=lw, color=color, fill=False) # Create free throw bottom arc bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color, linestyle='dashed') # Restricted Zone, it is an arc with 4ft radius from center of the hoop restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw, color=color) # Three point line # Create the side 3pt lines, they are 14ft long before they begin to arc corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=lw, color=color) corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=lw, color=color) # 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop # I just played around with the theta values until they lined up with the # threes three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw, color=color) # Center Court center_outer_arc = Arc((0, 422.5), 120, 120, theta1=180, theta2=0, linewidth=lw, color=color) center_inner_arc = Arc((0, 422.5), 40, 40, theta1=180, theta2=0, linewidth=lw, color=color) # List of the court elements to be plotted onto the axes court_elements = [ hoop, backboard, outer_box, inner_box, top_free_throw, bottom_free_throw, restricted, corner_three_a, corner_three_b, three_arc, center_outer_arc, center_inner_arc ] if outer_lines: # Draw the half court line, baseline and side out bound lines outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw, color=color, fill=False) court_elements.append(outer_lines) # Add the court elements onto the axes for element in court_elements: ax.add_patch(element) return ax
def golden_curve(max_n=10): """ Plot the golden curve """ # List of fibonacci numbers as (fn, fn-1) pair fibs = list(fibonacci(max_n)) # Reverse as we need to generate rectangles # from large -> small fibs.reverse() fig, ax = plt.subplots(1) last_x, last_y = fibs[0] # Make the plot size large enough to hold # the largest fibonacci number on both # x and y-axis. ax.set_xlim(0, last_x + 10) ax.set_ylim(0, last_y + 10) plt.axis('off') origin = [0, 0] p = 0 # Data for plotting arcs arc_points = [] rects = [] # Starting offset angle angle = 90 for i,(cur_fn, prev_fn) in enumerate(fibs): if i > max_n: break # Current arc's radius arc_radius = cur_fn if i in fourth_series(max_n): # Every 4th rectangle from the 2nd # rectangle onwards has its origin-x # point shifted by the fibonacci value origin[0] = origin[0] + cur_fn elif i in sixth_series(max_n): # Every 6th rectangle from the 5th # rectangle onwards has its origin-y # point shifted by the fibonacci value origin[1] = origin[1] + cur_fn if i%2 == 0: # Every 2nd rectangle has its orientation # switched from lxb to bxl cur_fn, prev_fn = prev_fn, cur_fn rectangle = Rectangle(origin, prev_fn, cur_fn, angle=0.0, antialiased=True) rects.append(rectangle) if i == 0: continue if i % 8 == 0: p += 1 continue if len(arc_points) == 8: continue r1 = rectangle # Calculate the rectangle's co-ordinates coords = [r1.get_xy(), [r1.get_x()+r1.get_width(), r1.get_y()], [r1.get_x()+r1.get_width(), r1.get_y()+r1.get_height()], [r1.get_x(), r1.get_y()+r1.get_height()]] # Successive arcs are centered on the points of rectangles # which is calculated as the p % 4 the item arc_points.append((coords[p % 4], arc_radius, angle)) # Every turn of the spiral we go clockwise by 90 degrees # means the starting angle reduces by 90. angle -= 90 # Reset to 0 if angle == -360: angle = 0 p += 3 for center, radius, angle in arc_points: print('Plotting arc at center',center,'radius',radius, 'angle',angle) arc = Arc(center, radius*2, radius*2, angle=angle, theta1=0, theta2=90.0, edgecolor='black', antialiased=True) ax.add_patch(arc) rect_pcs = PatchCollection(rects, facecolor='g', alpha=0.4, edgecolor='black') ax.add_collection(rect_pcs) plt.show()
def Pitch(ax, height=120, width=80, line_color="black", pitch_color="white", mode="full", pitch_linewidth=1): def int_angles(radius, h, k, line_x): """ Calculate the intersection angles of the arc above the D-boxes Parameters: radius (float): Radius of the arc h(float): x coordinate of the centre of the arc k(float): y coordiante of the centre of the arc line_x(float): x coordinate of the D-box or the line to be intersected by the arc Returns: theta1(float): First intersection angle theta2(float): Second intersection angle """ y1 = math.sqrt(radius**2 - (line_x - h)**2) + k y2 = math.sqrt(radius**2 - (line_x - h)**2) * -1 + k y = (y1 - y2) / 2 theta1 = math.degrees(math.asin(y / radius)) theta2 = 360 - theta1 return theta1, theta2 #Pitch Outline ax.plot([0, 0], [0, width], color=line_color, linewidth=pitch_linewidth) ax.plot([0, height], [width, width], color=line_color, linewidth=pitch_linewidth) ax.plot([height, height], [width, 0], color=line_color, linewidth=pitch_linewidth) ax.plot([height, 0], [0, 0], color=line_color, linewidth=pitch_linewidth) ##Halfway-line ax.plot([height / 2, height / 2], [0, width], color=line_color, linewidth=pitch_linewidth) #Left Penalty Area ax.plot([0, .15 * height], [.225 * width, .225 * width], color=line_color, linewidth=pitch_linewidth) ax.plot([.15 * height, .15 * height], [.225 * width, 0.775 * width], color=line_color, linewidth=pitch_linewidth) ax.plot([.15 * height, 0], [.775 * width, .775 * width], color=line_color, linewidth=pitch_linewidth) #Right Penalty Area ax.plot([.85 * height, height], [.15 * height, .15 * height], color=line_color, linewidth=pitch_linewidth) ax.plot([.85 * height, .85 * height], [.15 * height, .775 * width], color=line_color, linewidth=pitch_linewidth) ax.plot([.85 * height, height], [.775 * width, .775 * width], color=line_color, linewidth=pitch_linewidth) #6-yard box left ax.plot([0, .05 * height], [.375 * width, .375 * width], color=line_color, linewidth=pitch_linewidth) ax.plot([.05 * height, .05 * height], [.375 * width, width - .375 * width], color=line_color, linewidth=pitch_linewidth) ax.plot([0, .05 * height], [.625 * width, .625 * width], color=line_color, linewidth=pitch_linewidth) #6-yard box right ax.plot([.95 * height, height], [.375 * width, .375 * width], color=line_color, linewidth=pitch_linewidth) ax.plot([.95 * height, 114], [.375 * width, .625 * width], color=line_color, linewidth=pitch_linewidth) ax.plot([.95 * height, height], [.625 * width, .625 * width], color=line_color, linewidth=pitch_linewidth) #Prepare Circles centreCircle = plt.Circle((height / 2, width / 2), .076 * height, color=line_color, fill=False, zorder=5) centreSpot = plt.Circle((height / 2, width / 2), 0.8, color=line_color) leftPenSpot = plt.Circle((.1 * height, 40), 0.8, color=line_color) rightPenSpot = plt.Circle((.9 * height, 40), 0.8, color=line_color) #Prepare Arcs theta1, theta2 = int_angles(radius=height / 12, h=.1 * height, k=width / 2, line_x=.15 * height) leftArc = Arc((.1 * height, 40), height=0.15 * height, width=0.15 * height, angle=0, theta1=theta2, theta2=theta1, color=line_color, zorder=5) theta1, theta2 = int_angles(radius=height / 12, h=.9 * height, k=width / 2, line_x=.85 * height) rightArc = Arc((.9 * height, 40), height=0.15 * height, width=0.15 * height, angle=180, theta1=theta2, theta2=theta1, color=line_color, zorder=5) ##Add corner arcs left_bottom = Arc((0, 0), height=.05 * height, width=0.05 * height, angle=270, theta1=90, theta2=180, color=line_color, zorder=5) left_top = Arc((0, width), height=.05 * height, width=0.05 * height, angle=0, theta1=270, theta2=0, color=line_color, zorder=5) right_bottom = Arc((height, 0), height=.05 * height, width=0.05 * height, angle=0, theta1=90, theta2=180, color=line_color, zorder=5) right_top = Arc((height, width), height=.05 * height, width=0.05 * height, angle=90, theta1=90, theta2=180, color=line_color, zorder=5) #Goals ax.plot([0, 0], [.45 * width, .55 * width], color=line_color, linewidth=pitch_linewidth * 4) ax.plot([height, height], [.45 * width, .55 * width], color=line_color, linewidth=pitch_linewidth * 4) #Add patches ax.add_patch(leftArc) ax.add_patch(rightArc) ax.add_patch(centreCircle) ax.add_patch(centreSpot) ax.add_patch(leftPenSpot) ax.add_patch(rightPenSpot) if mode == "full": ax.add_patch(left_bottom) ax.add_patch(left_top) ax.add_patch(right_bottom) ax.add_patch(right_top) ax.set_aspect("equal") ax.axis("off") return ax
from matplotlib.patches import Wedge, Arc import matplotlib.pyplot as plt x = 6 y = 5 plt.xlim(0, x) plt.ylim(0, y) ax = plt.gca() figure_w = Wedge((3, 1), 2, 45, 135) # рисуем сектор (центр, радиус, углы) ax.add_patch(figure_w) figure_a = Arc((3, 1), 6, 6, 0, 45, 135, lw=3) ax.add_patch(figure_a) plt.grid() plt.show()
def createPitch(length, width, unity, linecolor): # in meters # Code by @JPJ_dejong """ creates a plot in which the 'length' is the length of the pitch (goal to goal). And 'width' is the width of the pitch (sideline to sideline). Fill in the unity in meters or in yards. """ #Set unity if unity == "meters": # Set boundaries if length >= 120.5 or width >= 75.5: return (str( "Field dimensions are too big for meters as unity, didn't you mean yards as unity?\ Otherwise the maximum length is 120 meters and the maximum width is 75 meters. Please try again" )) #Run program if unity and boundaries are accepted else: #Create figure fig = plt.figure() #fig.set_size_inches(7, 5) ax = fig.add_subplot(1, 1, 1) #Pitch Outline & Centre Line plt.plot([0, 0], [0, width], color=linecolor) plt.plot([0, length], [width, width], color=linecolor) plt.plot([length, length], [width, 0], color=linecolor) plt.plot([length, 0], [0, 0], color=linecolor) plt.plot([length / 2, length / 2], [0, width], color=linecolor) #Left Penalty Area plt.plot([16.5, 16.5], [(width / 2 + 16.5), (width / 2 - 16.5)], color=linecolor) plt.plot([0, 16.5], [(width / 2 + 16.5), (width / 2 + 16.5)], color=linecolor) plt.plot([16.5, 0], [(width / 2 - 16.5), (width / 2 - 16.5)], color=linecolor) #Right Penalty Area plt.plot([(length - 16.5), length], [(width / 2 + 16.5), (width / 2 + 16.5)], color=linecolor) plt.plot([(length - 16.5), (length - 16.5)], [(width / 2 + 16.5), (width / 2 - 16.5)], color=linecolor) plt.plot([(length - 16.5), length], [(width / 2 - 16.5), (width / 2 - 16.5)], color=linecolor) #Left 5-meters Box plt.plot([0, 5.5], [(width / 2 + 7.32 / 2 + 5.5), (width / 2 + 7.32 / 2 + 5.5)], color=linecolor) plt.plot([5.5, 5.5], [(width / 2 + 7.32 / 2 + 5.5), (width / 2 - 7.32 / 2 - 5.5)], color=linecolor) plt.plot([5.5, 0.5], [(width / 2 - 7.32 / 2 - 5.5), (width / 2 - 7.32 / 2 - 5.5)], color=linecolor) #Right 5 -eters Box plt.plot([length, length - 5.5], [(width / 2 + 7.32 / 2 + 5.5), (width / 2 + 7.32 / 2 + 5.5)], color=linecolor) plt.plot( [length - 5.5, length - 5.5], [(width / 2 + 7.32 / 2 + 5.5), width / 2 - 7.32 / 2 - 5.5], color=linecolor) plt.plot([length - 5.5, length], [width / 2 - 7.32 / 2 - 5.5, width / 2 - 7.32 / 2 - 5.5], color=linecolor) #Prepare Circles centreCircle = plt.Circle((length / 2, width / 2), 9.15, color=linecolor, fill=False) centreSpot = plt.Circle((length / 2, width / 2), 0.8, color=linecolor) leftPenSpot = plt.Circle((11, width / 2), 0.8, color=linecolor) rightPenSpot = plt.Circle((length - 11, width / 2), 0.8, color=linecolor) #Draw Circles ax.add_patch(centreCircle) ax.add_patch(centreSpot) ax.add_patch(leftPenSpot) ax.add_patch(rightPenSpot) #Prepare Arcs leftArc = Arc((11, width / 2), height=18.3, width=18.3, angle=0, theta1=308, theta2=52, color=linecolor) rightArc = Arc((length - 11, width / 2), height=18.3, width=18.3, angle=0, theta1=128, theta2=232, color=linecolor) #Draw Arcs ax.add_patch(leftArc) ax.add_patch(rightArc) #Axis titles #check unity again elif unity == "yards": #check boundaries again if length <= 95: return (str("Didn't you mean meters as unity?")) elif length >= 131 or width >= 101: return (str( "Field dimensions are too big. Maximum length is 130, maximum width is 100" )) #Run program if unity and boundaries are accepted else: #Create figure fig = plt.figure() #fig.set_size_inches(7, 5) ax = fig.add_subplot(1, 1, 1) #Pitch Outline & Centre Line plt.plot([0, 0], [0, width], color=linecolor) plt.plot([0, length], [width, width], color=linecolor) plt.plot([length, length], [width, 0], color=linecolor) plt.plot([length, 0], [0, 0], color=linecolor) plt.plot([length / 2, length / 2], [0, width], color=linecolor) #Left Penalty Area plt.plot([18, 18], [(width / 2 + 18), (width / 2 - 18)], color=linecolor) plt.plot([0, 18], [(width / 2 + 18), (width / 2 + 18)], color=linecolor) plt.plot([18, 0], [(width / 2 - 18), (width / 2 - 18)], color=linecolor) #Right Penalty Area plt.plot([(length - 18), length], [(width / 2 + 18), (width / 2 + 18)], color=linecolor) plt.plot([(length - 18), (length - 18)], [(width / 2 + 18), (width / 2 - 18)], color=linecolor) plt.plot([(length - 18), length], [(width / 2 - 18), (width / 2 - 18)], color=linecolor) #Left 6-yard Box plt.plot([0, 6], [(width / 2 + 7.32 / 2 + 6), (width / 2 + 7.32 / 2 + 6)], color=linecolor) plt.plot([6, 6], [(width / 2 + 7.32 / 2 + 6), (width / 2 - 7.32 / 2 - 6)], color=linecolor) plt.plot([6, 0], [(width / 2 - 7.32 / 2 - 6), (width / 2 - 7.32 / 2 - 6)], color=linecolor) #Right 6-yard Box plt.plot([length, length - 6], [(width / 2 + 7.32 / 2 + 6), (width / 2 + 7.32 / 2 + 6)], color=linecolor) plt.plot([length - 6, length - 6], [(width / 2 + 7.32 / 2 + 6), width / 2 - 7.32 / 2 - 6], color=linecolor) plt.plot([length - 6, length], [(width / 2 - 7.32 / 2 - 6), width / 2 - 7.32 / 2 - 6], color=linecolor) #Prepare Circles; 10 yards distance. penalty on 12 yards centreCircle = plt.Circle((length / 2, width / 2), 10, color=linecolor, fill=False) centreSpot = plt.Circle((length / 2, width / 2), 0.8, color=linecolor) leftPenSpot = plt.Circle((12, width / 2), 0.8, color=linecolor) rightPenSpot = plt.Circle((length - 12, width / 2), 0.8, color=linecolor) #Draw Circles ax.add_patch(centreCircle) ax.add_patch(centreSpot) ax.add_patch(leftPenSpot) ax.add_patch(rightPenSpot) #Prepare Arcs leftArc = Arc((11, width / 2), height=20, width=20, angle=0, theta1=312, theta2=48, color=linecolor) rightArc = Arc((length - 11, width / 2), height=20, width=20, angle=0, theta1=130, theta2=230, color=linecolor) #Draw Arcs ax.add_patch(leftArc) ax.add_patch(rightArc) #Tidy Axes plt.axis('off') return fig, ax
def CreatePitch(i): """Function that draws a pitch with dimensions 105x68""" #Create figure fig = plt.figure(i, figsize=(6.4 * 2, 4.8 * 2)) ax = fig.add_subplot(1, 1, 1) #Pitch Outline & Centre Line plt.plot([0, 0], [0, 68], color="black") plt.plot([0, 105], [68, 68], color="black") plt.plot([105, 105], [68, 0], color="black") plt.plot([105, 0], [0, 0], color="black") plt.plot([52.5, 52.5], [0, 68], color="black") #Left Penalty Area plt.plot([16.5, 16.5], [13.84, 54.16], color="black") plt.plot([0, 16.5], [54.16, 54.16], color="black") plt.plot([16.5, 0], [13.84, 13.84], color="black") #Left goal plt.plot([-2, -2], [30.34, 37.66], color="black") plt.plot([-2, 0], [30.34, 30.34], color="black") plt.plot([0, -2], [37.66, 37.66], color="black") #Right goal plt.plot([107, 107], [30.34, 37.66], color="black") plt.plot([107, 105], [30.34, 30.34], color="black") plt.plot([105, 107], [37.66, 37.66], color="black") #Right Penalty Area plt.plot([105, 88.5], [54.16, 54.16], color="black") plt.plot([88.5, 88.5], [54.16, 13.84], color="black") plt.plot([88.5, 105], [13.84, 13.84], color="black") #Left Small Area plt.plot([0, 5.5], [43.16, 43.16], color="black") plt.plot([5.5, 5.5], [43.16, 24.84], color="black") plt.plot([5.5, 0], [24.84, 24.84], color="black") #Right Small Area plt.plot([105, 99.5], [43.16, 43.16], color="black") plt.plot([99.5, 99.5], [43.16, 24.84], color="black") plt.plot([99.5, 105], [24.84, 24.84], color="black") #Prepare Circles centreCircle = plt.Circle((52.5, 34), 9.15, color="black", fill=False) centreSpot = plt.Circle((52.5, 34), 0.4, color="black", fill=False) leftPenSpot = plt.Circle((11, 34), 0.4, color="black", fill=False) rightPenSpot = plt.Circle((94, 34), 0.4, color="black", fill=False) #Draw Circles ax.add_patch(centreCircle) ax.add_patch(centreSpot) ax.add_patch(leftPenSpot) ax.add_patch(rightPenSpot) #Prepare Arcs leftArc = Arc((11, 34), height=16.4, width=18.3, angle=0, theta1=310, theta2=50, color="black") rightArc = Arc((94, 34), height=16.4, width=18.3, angle=0, theta1=130, theta2=230, color="black") #Draw Arcs ax.add_patch(leftArc) ax.add_patch(rightArc) #Tidy Axes plt.gca().invert_yaxis() return
def onDrawRose(self, event): """ Rose Diagram Options """ try: # the 'except' for this 'try' is about 200 lines ahead! i = self.file_i ddirRb = self.rbddir.GetValue() strkRb = self.rbstrk.GetValue() trndRb = self.rbtrd.GetValue() r360 = self.rb360.GetValue() r180 = self.rb180.GetValue() frequency = self.rbfreq.GetValue() weighted = self.rbwgt.GetValue() petal = self.spin.GetValue() outer_circ = self.spin2.GetValue() inner_rings = self.spin3.GetValue() diagonals = self.spin4.GetValue() fillcolor = self.fcolor edgecolor = self.lcolor fontsize = self.fontSize showMean = self.cb_mean.GetValue() meancolor = self.mcolor meanwidth = self.spin5.GetValue() ring_steps = inner_rings / float(outer_circ) grid_col = 'grey' grid_width = 0.5 self.plotaxes2.cla() axes = self.plotaxes2 self.plotaxes2.set_axis_off() # create empty lists Azimuth = [] Dip = [] ddir = [] dp = [] strk = [] trd = [] plng = [] # what kind of data was selected if self.nametype == 1: # 1 == itemPlanar ddir = self.Pazim[i] dp = self.Pdip[i] strk = self.Pstrike[i] if self.Pidx[i].startswith('D'): # dip-dir data name = '[P(dd)] %s' % self.Pname[i] else: # right-hand data name = '[P(rh)] %s' % self.Pname[i] elif self.nametype == 2: # 2 == itemLinear trd = self.Lazim[i] plng = self.Ldip[i] name = '[L] %s' % self.Lname[i] elif self.nametype == 4: # 2 == itemFault ddir = self.Fazim[i] dp = self.Fdip[i] strk = self.Fstrike[i] trd = self.Ftrend[i] plng = self.Fplunge[i] name = '[F] %s' % self.Fname[i] else: pass # check if DipDir or Strike or Trend if ddirRb: #~ print 'ddier' Azimuth = ddir Dip = dp elif strkRb: #~ print 'strike' Azimuth = strk Dip = dp elif trndRb: #~ print 'trend' Azimuth = trd Dip = plng # nothing selected or wrong kind of data choosen if Azimuth == []: raise AttributeError # convert azimuth to modulo 180 or modulo 360 azimMod = [] if r180: #test if 180deg rose was selected for az in Azimuth: if 90.0 < az <= 180.0: azimMod.append(az + 180.0) elif 180.0 <= az <= 270.0: azimMod.append(az - 180.0) else: azimMod.append(az) else: azimMod = Azimuth # calculate mean direction and circular standar deviation # from Fisher 1993, Statistical Analyis of circular data, p.32-33 ndata = len(azimMod) cosTheta = [np.cos(np.radians(az)) for az in azimMod] sinTheta = [np.sin(np.radians(az)) for az in azimMod] C = np.sum(cosTheta) S = np.sum(sinTheta) R = np.sqrt(C * C + S * S) Rbar = R / ndata V = 1.0 - Rbar ThetaBar = np.arctan2(C, S) ThetaBarDeg = np.degrees(ThetaBar) if 0.0 <= ThetaBarDeg < 90.0: ThetaBarDeg = -(ThetaBarDeg - 90.0) elif 90.0 <= ThetaBarDeg <= 180.0: ThetaBarDeg = 540.0 + (-ThetaBarDeg - 90.0) else: ThetaBarDeg = -ThetaBarDeg + 90.0 # assuming a unimodal Von Mises distribution.. # from Fisher 1993, Statistical Analyis of circular data, p.88-89 # if data does not follows a unimodal distribution (or has only one value), skip plotConfidence = True try: if Rbar < 0.53: khatml = 2.0 * Rbar + (Rbar**3.0) + (5 * (Rbar**5.0) / 6.0) elif 0.53 <= Rbar <= 0.85: khatml = -0.4 + 1.39 * Rbar + 0.43 / V else: # Rbar > 0.85: khatml = 1.0 / (Rbar**3.0 - 4.0 * (Rbar**2.0) + 3.0 * Rbar) if khatml < 2.0: stuff = [khatml - 2.0 * ((ndata * khatml)**-1.0), 0.0] khat = np.max(stuff) else: #khat_ml => 2 khat = ((ndata - 1.0)**3.0) * khatml / (ndata**3.0 + ndata) sigma_vm = 1.0 / np.sqrt(ndata * Rbar * khat) confidenceUp = np.degrees(ThetaBar + np.arcsin(1.9604 * sigma_vm)) confidenceDw = np.degrees(ThetaBar - np.arcsin(1.9604 * sigma_vm)) confidence = np.degrees(np.arcsin(1.9604 * sigma_vm)) except: plotConfidence = False pass if np.isnan(confidence): plotConfidence = False # convert azimuths from compass to polar azimPolar = [] for az in azimMod: ang = 360.0 - az + 90.0 if ang >= 360.0: ang = ang - 360.0 azimPolar.append(ang) # bins for the histogram nbins = np.arange(0., 360.1, petal) # test if weighted rose diagram was selected if weighted: rose_hist = np.histogram(azimPolar, nbins, weights=Dip) #,normed=True,new=True) weights_sum = sum(Dip) petal_perc = [i * 100.0 / weights_sum for i in rose_hist[0]] else: rose_hist = np.histogram(azimPolar, nbins) #,new=True) petal_perc = [i * 100.0 / len(azimPolar) for i in rose_hist[0]] petal_mid = [i + petal / 2 for i in nbins] petal_dens = [i / outer_circ for i in petal_perc] petal_max = max(petal_dens) * outer_circ # draws the petals for j in range(len(petal_dens)): x = [] y = [] #define limits of petal start = np.radians(petal_mid[j] + petal / 2) stop = np.radians(petal_mid[j] - petal / 2) #start drawing the petals (triangles: x0,y0 -> x2,y2 -> x3,y3 -> x0,y0) x.append(0) y.append(0) x2 = petal_dens[j] * np.cos(start) y2 = petal_dens[j] * np.sin(start) x.append(x2) y.append(y2) x3 = petal_dens[j] * np.cos(stop) y3 = petal_dens[j] * np.sin(stop) x.append(x3) y.append(y3) x.append(0) y.append(0) xy = np.array([x, y]) #convert lists to numpy array xy2 = xy.transpose( ) # transpose array from shape (2,4) to shape (4,2) l_petal = Polygon(xy2, fc=fillcolor, ec=edgecolor) axes.add_patch(l_petal) # draws the circle (or half-circle), and adds decorations (tick marks, rings, etc) if r360: #full-circle rose x_cross = [0, 1, 0, -1, 0] y_cross = [0, 0, 1, 0, -1] axes.plot(x_cross, y_cross, 'k+', markersize=8) circ = Circle((0, 0), radius=1, edgecolor='black', facecolor='none', clip_box='None', zorder=0) axes.add_patch(circ) axes.text(0.01, 1.025, 'N', family='sans-serif', size=fontsize, horizontalalignment='center') axes.text(1.05, 0, '%d %%' % outer_circ, family='sans-serif', size=fontsize, verticalalignment='center') axes.text(-1.05, 0, '%d %%' % outer_circ, family='sans-serif', size=fontsize, verticalalignment='center', horizontalalignment='right') for i in np.arange(0.0, 1.0, ring_steps): ring = Circle((0, 0), radius=i, fc='none', ec=grid_col, lw=grid_width, zorder=0) axes.add_patch(ring) for i in np.arange(0.0, 90.0, diagonals): diag = Line2D( (np.sin(np.radians(i)), np.sin(np.radians(i + 180))), (np.cos(np.radians(i)), np.cos(np.radians(i + 180))), c=grid_col, lw=grid_width, zorder=0) axes.add_line(diag) for i in np.arange(90.0, 180.0, diagonals): diag = Line2D( (np.sin(np.radians(i)), np.sin(np.radians(i + 180))), (np.cos(np.radians(i)), np.cos(np.radians(i + 180))), c=grid_col, lw=grid_width, zorder=0) axes.add_line(diag) # some texts.. axes.text(-1.22, 0.95, '%s' % self.Name, family='sans-serif', size=fontsize, horizontalalignment='left') axes.text(-1.22, 0.85, 'n = %d' % len(azimPolar), family='sans-serif', size=fontsize, horizontalalignment='left') axes.text(-1.22, 0.77, 'max = %.2f %%' % petal_max, family='sans-serif', size=fontsize, horizontalalignment='left') if weighted: axes.text(-1.22, 0.67, '(weighted)', family='sans-serif', size=fontsize, horizontalalignment='left') else: axes.text(-1.22, 0.67, '(frequency)', family='sans-serif', size=fontsize, horizontalalignment='left') axes.text(0.7, 0.95, u'Mean dir.: %3.1f°' % ThetaBarDeg, family='sans-serif', size=fontsize, horizontalalignment='left') if plotConfidence: axes.text(0.7, 0.87, u'95 %% conf.: ± %3.1f°' % confidence, family='sans-serif', size=fontsize, horizontalalignment='left') # marks for means direction and confidence interval if showMean: if plotConfidence: confcirc = Arc((0, 0), width=2.08, height=2.08, angle=0.0, theta1=confidenceDw, theta2=confidenceUp, ec=meancolor, lw=meanwidth, fill=None, zorder=0) axes.add_patch(confcirc) x0 = np.cos(ThetaBar) + np.cos(ThetaBar) * 0.11 x1 = np.cos(ThetaBar) + np.cos(ThetaBar) * 0.065 y0 = np.sin(ThetaBar) + np.sin(ThetaBar) * 0.11 y1 = np.sin(ThetaBar) + np.sin(ThetaBar) * 0.065 lin = Line2D((x0, x1), (y0, y1), lw=meanwidth, c=meancolor) axes.add_line(lin) self.plotaxes2.set_xlim(-1.3, 1.3) self.plotaxes2.set_ylim(-1.15, 1.15) self.roseCanvas.draw() else: #half-circle rose x_cross = [0, 1, 0, -1] y_cross = [0, 0, 1, 0] axes.plot(x_cross, y_cross, 'k+', markersize=8) circ = Arc((0, 0), width=2, height=2, angle=0.0, theta1=0.0, theta2=180.0, ec=None, fill=None, zorder=0) axes.add_patch(circ) axes.text(0.01, 1.025, 'N', family='sans-serif', size=fontsize, horizontalalignment='center') axes.text(1.05, 0, '%d %%' % outer_circ, family='sans-serif', size=fontsize, verticalalignment='center') axes.text(-1.05, 0, '%d %%' % outer_circ, family='sans-serif', size=fontsize, verticalalignment='center', horizontalalignment='right') for i in np.arange(0.0, 1.0, ring_steps): ring = Arc((0, 0), width=i * 2, height=i * 2, angle=0.0, theta1=0.0, theta2=180.0, ec=grid_col, fill=None, lw=grid_width, zorder=0) axes.add_patch(ring) for i in np.arange(0.0, 90.1, diagonals): diag = Line2D((0, np.sin(np.radians(i))), (0, np.cos(np.radians(i))), c=grid_col, lw=grid_width, zorder=0) axes.add_line(diag) for i in np.arange(270.0, 360.0, diagonals): diag = Line2D((0, np.sin(np.radians(i))), (0, np.cos(np.radians(i))), c=grid_col, lw=grid_width, zorder=0) axes.add_line(diag) # some texts.. axes.text(-1.22, 0.95, '%s' % self.Name, family='sans-serif', size=fontsize, horizontalalignment='left') axes.text(-1.22, 0.85, 'n = %d' % len(azimPolar), family='sans-serif', size=fontsize, horizontalalignment='left') axes.text(-1.22, 0.77, 'max = %.2f %%' % petal_max, family='sans-serif', size=fontsize, horizontalalignment='left') if weighted: axes.text(-1.22, 0.67, '(weighted)', family='sans-serif', size=fontsize, horizontalalignment='left') else: axes.text(-1.22, 0.67, '(frequency)', family='sans-serif', size=fontsize, horizontalalignment='left') axes.text(0.7, 0.95, u'Mean dir.: %3.1f°' % ThetaBarDeg, family='sans-serif', size=fontsize, horizontalalignment='left') if plotConfidence: axes.text(0.7, 0.87, u'95 %% conf.: ± %3.1f°' % confidence, family='sans-serif', size=fontsize, horizontalalignment='left') # marks for means direction and confidence interval if showMean: if plotConfidence: confcirc = Arc((0, 0), width=2.08, height=2.08, angle=0.0, theta1=confidenceDw, theta2=confidenceUp, ec=meancolor, lw=meanwidth, fill=None, zorder=0) axes.add_patch(confcirc) x0 = np.cos(ThetaBar) + np.cos(ThetaBar) * 0.11 x1 = np.cos(ThetaBar) + np.cos(ThetaBar) * 0.065 y0 = np.sin(ThetaBar) + np.sin(ThetaBar) * 0.11 y1 = np.sin(ThetaBar) + np.sin(ThetaBar) * 0.065 lin = Line2D((x0, x1), (y0, y1), lw=meanwidth, c=meancolor) axes.add_line(lin) self.plotaxes2.set_xlim(-1.3, 1.3) self.plotaxes2.set_ylim(-0.05, 1.15) self.roseCanvas.draw() self.mainframe.sb.SetStatusText( 'Rose diagram plotted with petals of %d degrees' % petal) #~ # this is from the 'try' right after 'def DrawRose' except AttributeError: dlg = wx.MessageDialog( None, 'No file(s) selected (highlighted).\n\nOr maybe you are trying to make a diagram\nfor the wrong kind of data (like "trend" for planar data)', 'Oooops!', wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() pass
def transform_path_non_affine(self, path): vertices = path.vertices codes = path.codes steps = path._interpolation_steps x, y = np.array(list(zip(*vertices))) if len(vertices) > 1 and not isinstance(steps, int): if steps == 'inf_circle': z = x + y * 1j new_vertices = [] new_codes = [] for i in range(len(z) - 1): az = self._axes._moebius_z(0.5 * (z[i] + z[i+1])) zz = self._axes._moebius_z(z[i:i+2]) ax, ay = az.real, az.imag bz, cz = zz bx, cx = zz.real - ax by, cy = zz.imag - ay k = 2 * (bx * cy - by * cx) xm = (cy * (bx ** 2 + by ** 2) - by * (cx ** 2 + cy ** 2)) / k + ax ym = (bx * (cx ** 2 + cy ** 2) - cx * (bx ** 2 + by ** 2)) / k + ay zm = xm + ym * 1j d = 2 * abs(zm - az) ang0 = np.angle(bz - zm, deg=True) % 360 ang1 = np.angle(cz - zm, deg=True) % 360 reverse = ang0 > ang1 if reverse: ang0, ang1 = ang1, ang0 arc = Arc([xm, ym], d, d, theta1=ang0, theta2=ang1, transform=self._axes.transMoebius) arc_path = arc.get_patch_transform().transform_path(arc.get_path()) if reverse: new_vertices.append(arc_path.vertices[::-1]) else: new_vertices.append(arc_path.vertices) new_codes.append(arc_path.codes) new_vertices = np.concatenate(new_vertices) new_codes = np.concatenate(new_codes) elif steps == 'center_circle': points = self._axes._get_key("path.default_interpolation") z = self._axes._moebius_z(x + y * 1j) ang0, ang1 = np.angle(z[0:2]) % TWO_PI ccw = (ang1 - ang0) % TWO_PI < np.pi ix, iy = [np.real(z[0])], [np.imag(z[0])] new_codes = [Path.MOVETO] for i in range(len(z) - 1): zz = z[i:i + 2] r0, r1 = np.abs(zz) ang0, ang1 = np.angle(zz) % TWO_PI if ccw: if ang0 > ang1: ang1 += TWO_PI else: if ang1 > ang0: ang0 += TWO_PI r = np.linspace(r0, r1, points)[1:] ang = np.linspace(ang0, ang1, points)[1:] ix += list(np.cos(ang) * r) iy += list(np.sin(ang) * r) new_codes += (points - 1) * [Path.LINETO] new_vertices = list(zip(ix, iy)) else: raise ValueError("Interpolation must be either an integer, 'inf_circle' or 'center_circle'") else: if steps == 0: steps = self._axes._get_key("path.default_interpolation") ix, iy = ([x[0:1]], [y[0:1]]) for i in range(len(x) - 1): x0, x1 = x[i:i + 2] y0, y1 = y[i:i + 2] tx = self._axes.real_interp1d([x0, x1], steps)[1:] if abs(x0 - x1) > EPSILON: ty = y0 + (tx - x0) * (y1 - y0) / (x1 - x0) else: ty = self._axes.imag_interp1d([y0, y1], steps)[1:] ix.append(tx) iy.append(ty) if codes is not None: new_codes = Path.LINETO * np.ones((len(codes) - 1) * steps + 1) new_codes[0::steps] = codes else: new_codes = None new_vertices = self.transform_non_affine(list(zip(np.concatenate(ix), np.concatenate(iy)))) new_codes = codes return Path(new_vertices, new_codes, 1)