# plt.gca().add_patch(cir) dt = 2 * pi / len(slist) for n in slist: p = dim * [0.0] p[0] = r * cos(t) p[1] = r * sin(t) pos[n] = np.array(p) t = t + dt wedge = Wedge((0, 0), r * 210, 0, 360, width=200 * 1.0, fc=plt.cm.winter( float(listcomattr[s][1] + abs(minwtl)) / (maxwtl + abs(minwtl))), linewidth=0.0, alpha=0.55) plt.gca().add_patch(wedge) if len(slist) > 2 and len(slist) <= 10: r = float(2 * s + 16) print r # print listcomattr[s][0], listcomattr[s][1], len(slist) # cir = plt.Circle((0,0), radius=r*200, alpha =0.2, fc=plt.cm.Greens(listcomattr[s][1]), linewidth = 0.0) # plt.gca().add_patch(cir) dt = 2 * pi * minshellsize * 1.0 / (maxshellsize) for n in slist:
def plot_polar_bar_plots(radial_bins, metric="MAE", addTitle=None, returnFig=False): assert type(metric) == str and metric in [ "MAE", "STD", "RMSE" ], "metric must be either 'MAE' (default) or 'STD'." if metric == "MAE": baseTitle = "Polar Bar Plots of MAE vs. Joint Angle" xLabel = "Log MAE (in deg.)" maxValue = np.log10(radial_bins["maxMAE"]) + 2 offset = 2 elif metric == 'STD': baseTitle = "Polar Bar Plots of Error Std Dev vs. Joint Angle" xLabel = "Log Error Std Dev (in deg.)" maxValue = np.log10(radial_bins["maxSTD"]) + 2 offset = 2 elif metric == 'RMSE': baseTitle = "Polar Bar Plots of RMSE vs. Joint Angle" xLabel = "Log RMSE (in deg.)" maxValue = np.log10(radial_bins["maxRMSE"]) + 2 offset = 2 # assert maxValue<3.3, "Bounds not configured for values this large. Please check values again and determine if bounds need to be changed." if addTitle is None: title = baseTitle else: assert type(addTitle) == str, "title must be a string." title = baseTitle + "\n" + addTitle subTitles = [ "All\nAvailable\nStates", "The\nBio-Inspired\nSet", "Motor Position\nand\nVelocity Only", "All\nMotor\nStates" ] fig = plt.figure(figsize=(20, 12)) plt.suptitle(title, fontsize=14) ax1 = plt.subplot(221) ax2 = plt.subplot(222) ax3 = plt.subplot(223) ax3.set_xlabel(xLabel, ha="center") ax3.xaxis.set_label_coords(0.8, -0.1) ax4 = plt.subplot(224) axs = [ax1, ax2, ax3, ax4] slices = radial_bins['bins'] thetaRays = np.arange(0, np.pi + 1e-3, np.pi / slices) groups = ["all", "bio", "kinapprox", "allmotor"] for i in range(4): for j in range(len(thetaRays) - 1): bin_name = ('{:0.1f}'.format(180 * thetaRays[j] / np.pi) + " to " + '{:0.1f}'.format(180 * thetaRays[j + 1] / np.pi)) if j % 2 == 0: axs[i].add_patch( Wedge((0, 0), 3.3, (180 / np.pi) * thetaRays[j], (180 / np.pi) * thetaRays[j + 1], color="0.85")) axs[i].add_patch( Wedge((0, 0), np.log10(radial_bins[groups[i]][bin_name][metric]) + offset, (180 / np.pi) * thetaRays[j], (180 / np.pi) * thetaRays[j + 1], color=colors[i], alpha=0.65)) axs[i].set_aspect('equal') axs[i].set_ylim([0, 3.3]) axs[i].set_xlim([-3.3, 3.3]) xticks = np.arange(0, 3 + 1e-3, 1) xticks = np.concatenate( [-np.array(list(reversed(xticks[1:]))), xticks[1:]]) axs[i].set_xticks(xticks) axs[i].set_xticklabels([ r"$10^{1}$", r"$10^{0}$", r"$10^{-1}$", r"$10^{-1}$", r"$10^{0}$", r"$10^{1}$" ]) axs[i].add_patch(Wedge((0, 0), 1, 0, 360, color='w')) xticksMinor = np.concatenate([ np.linspace(10**(i), 10**(i + 1), 10)[1:-1] for i in range(-1, 1) ]) xticksMinor = np.concatenate( [-np.array(list(reversed(xticksMinor))), xticksMinor]) xticksMinor = [ np.sign(el) * (np.log10(abs(el)) + 2) for el in xticksMinor ] axs[i].set_xticks(xticksMinor, minor=True) yticks = list(np.arange(0, 3 + 1e-3, 1)) axs[i].set_yticks(yticks[1:]) axs[i].set_yticklabels(["" for tick in axs[i].get_yticks()]) yticksMinor = np.concatenate([ np.linspace(10**(i), 10**(i + 1), 10)[1:-1] for i in range(-1, 1) ]) yticksMinor = [ np.sign(el) * (np.log10(abs(el)) + 2) for el in yticksMinor ] axs[i].set_yticks(yticksMinor, minor=True) radii = list(axs[i].get_yticks()) theta = np.linspace(0, np.pi, 201) for radius in radii: axs[i].plot([radius * np.cos(el) for el in theta], [radius * np.sin(el) for el in theta], "k", lw=0.5) axs[i].plot([1, 3.3], [0, 0], 'k', linewidth=1.5) # double lw because of ylim axs[i].plot([-3.3, -1], [0, 0], 'k', linewidth=1.5) # double lw because of ylim axs[i].plot([0, 0], [1, 3.3], 'k', linewidth=0.5) axs[i].text(0, 0.25, subTitles[i], color=colors[i], horizontalalignment='center', verticalalignment='center', fontsize=16) axs[i].spines['bottom'].set_position('zero') axs[i].spines['left'].set_position('zero') axs[i].spines['bottom'].set_visible(False) axs[i].spines['left'].set_visible(False) axs[i].spines['top'].set_visible(False) axs[i].spines['right'].set_visible(False) # maxError = 4.1 # axs[i].set_aspect('equal') # axs[i].set_ylim([0,maxError]) # axs[i].set_xlim([-maxError,maxError]) # xticks = list(np.arange(-np.floor(maxError),np.floor(maxError)+1e-3,1)) # axs[i].set_xticks(xticks) # axs[i].set_xticklabels([r"$10^{2}$",r"$10^{1}$",r"$10^{0}$",r"$10^{-1}$","0",r"$10^{-1}$",r"$10^{0}$",r"$10^{1}$",r"$10^{2}$"]) # xticksMinor = np.concatenate( # [np.linspace(10**(i),10**(i+1),10)[1:-1] for i in range(-1,2)] # ) # xticksMinor = np.concatenate( # [ # -np.array(list(reversed(xticksMinor))), # xticksMinor # ] # ) # xticksMinor = [np.sign(el)*(np.log10(abs(el))+2) for el in xticksMinor] # axs[i].set_xticks(xticksMinor,minor=True) # # yticks = [0,1,2,3,4] # axs[i].set_yticks(yticks) # axs[i].set_yticklabels(["" for tick in axs[i].get_yticks()]) # yticksMinor = np.concatenate( # [np.linspace(10**(i),10**(i+1),10)[1:-1] for i in range(-1,2)] # ) # yticksMinor = [np.sign(el)*(np.log10(abs(el))+2) for el in yticksMinor] # axs[i].set_yticks(yticksMinor,minor=True) # # radii = list(axs[i].get_yticks()) # theta = np.linspace(0,np.pi,201) # for radius in radii: # axs[i].plot( # [radius*np.cos(el) for el in theta], # [radius*np.sin(el) for el in theta], # "k", # lw=0.5 # ) # # for ray in thetaRays: # axs[i].plot( # [0,maxError*np.cos(ray)], # [0,maxError*np.sin(ray)], # 'k', # lw=0.5 # ) # axs[i].spines['bottom'].set_position('zero') # axs[i].spines['left'].set_position('zero') # axs[i].spines['top'].set_visible(False) # axs[i].spines['right'].set_visible(False) if returnFig == True: return (fig)
def gauge(labels=['LOW', 'MEDIUM', 'HIGH', 'VERY HIGH', 'EXTREME'], colors='jet_r', cat=1, title='', fname='./gauge.png'): """ some sanity checks first """ N = len(labels) if cat > N: raise Exception( "\n\nThe category ({}) is greated than the length\nof the labels ({})" .format(cat, N)) """ if colors is a string, we assume it's a matplotlib colormap and we discretize in N discrete colors """ if isinstance(colors, str): cmap = cm.get_cmap(colors, N) cmap = cmap(np.arange(N)) colors = cmap[::-1, :].tolist() if isinstance(colors, list): if len(colors) == N: colors = colors[::-1] else: raise Exception( "\n\nnumber of colors {} not equal to number of categories{}\n" .format(len(colors), N)) """ begins the plotting """ fig, ax = plt.subplots() ang_range, mid_points = degree_range(N) labels = labels[::-1] """ plots the sectors and the arcs """ patches = [] for ang, c in zip(ang_range, colors): # sectors patches.append(Wedge((0., 0.), .4, *ang, facecolor='w', lw=2)) # arcs patches.append( Wedge((0., 0.), .4, *ang, width=0.10, facecolor=c, lw=2, alpha=0.5)) [ax.add_patch(p) for p in patches] """ set the labels (e.g. 'LOW','MEDIUM',...) """ for mid, lab in zip(mid_points, labels): ax.text(0.35 * np.cos(np.radians(mid)), 0.35 * np.sin(np.radians(mid)), lab, \ horizontalalignment='center', verticalalignment='center', fontsize=14, \ fontweight='bold', rotation = rot_text(mid)) """ set the bottom banner and the title """ r = Rectangle((-0.4, -0.1), 0.8, 0.1, facecolor='w', lw=2) ax.add_patch(r) ax.text(0, -0.05, title, horizontalalignment='center', \ verticalalignment='center', fontsize=22, fontweight='bold') """ plots the arrow now """ pos = mid_points[abs(cat - N)] ax.arrow(0, 0, 0.225 * np.cos(np.radians(pos)), 0.225 * np.sin(np.radians(pos)), \ width=0.04, head_width=0.09, head_length=0.1, fc='k', ec='k') ax.add_patch(Circle((0, 0), radius=0.02, facecolor='k')) ax.add_patch(Circle((0, 0), radius=0.01, facecolor='w', zorder=11)) """ removes frame and ticks, and makes axis equal and tight """ ax.set_frame_on(False) ax.axes.set_xticks([]) ax.axes.set_yticks([]) ax.axis('equal') plt.tight_layout() fig.savefig(fname, dpi=200) fig.pyplot(fname, dpi=200)
def patchValMap(vals, xvec=None, yvec=None, ax=None, cMin=None, cMax=None, logScale=None, label=None, dx=1, dy=None, cTrim=0, **kwargs): """Plot previously generated (generateVecMatrix) y map (category). Parameters ---------- vals : iterable Data values to show. xvec : dict {i:num} dict (must match vals.shape[0]) ymap : iterable vector for x axis (must match vals.shape[0]) ax : mpl.axis axis to plot, if not given a new figure is created cMin/cMax : float minimum/maximum color values cTrim : float [0] use trim value to exclude outer cTrim percent of data from color scale logScale : bool logarithmic colour scale [min(vals)>0] label : string colorbar label ** kwargs: * circular : bool Plot in polar coordinates. """ if cMin is None: cMin = np.min(vals) # cMin = np.nanquantile(vals, cTrim/100) if cMax is None: cMax = np.max(vals) # cMin = np.nanquantile(vals, 1-cTrim/100) if logScale is None: logScale = (cMin > 0.0) norm = None if logScale and cMin > 0: norm = LogNorm(vmin=cMin, vmax=cMax) else: norm = Normalize(vmin=cMin, vmax=cMax) if ax is None: ax = plt.subplots()[1] recs = [] circular = kwargs.pop('circular', False) if circular: recs = [None] * len(xvec) if dy is None: # map y values to unique ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))} xyMap = {} for i, y in enumerate(yvec): if y not in xyMap: xyMap[y] = [] xyMap[y].append(i) # maxR = max(ymap.values()) # what's that for? not used dR = 1 / (len(ymap.values()) + 1) # dOff = np.pi / 2 # what's that for? not used for y, xIds in xyMap.items(): r = 1. - dR * (ymap[y] + 1) # ax.plot(r * np.cos(xvec[xIds]), # r * np.sin(xvec[xIds]), 'o') # print(y, ymap[y]) for i in xIds: phi = xvec[i] # x = r * np.cos(phi) # what's that for? not used y = r * np.sin(phi) dPhi = (xvec[1] - xvec[0]) recs[i] = Wedge((0., 0.), r + dR / 1.5, (phi - dPhi) * 360 / (2 * np.pi), (phi + dPhi) * 360 / (2 * np.pi), width=dR, zorder=1 + r) # if i < 5: # ax.text(x, y, str(i)) # pg.wait() else: raise ("Implementme") else: if dy is None: # map y values to unique ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))} for i in range(len(vals)): recs.append( Rectangle((xvec[i] - dx / 2, ymap[yvec[i]] - 0.5), dx, 1)) else: for i in range(len(vals)): recs.append( Rectangle((xvec[i] - dx / 2, yvec[i] - dy / 2), dx, dy)) ax.set_xlim(min(xvec) - dx / 2, max(xvec) + dx / 2) ax.set_ylim(len(ymap) - 0.5, -0.5) pp = PatchCollection(recs) # ax.clear() col = ax.add_collection(pp) pp.set_edgecolor(None) pp.set_linewidths(0.0) if 'alpha' in kwargs: pp.set_alpha(kwargs['alpha']) if circular: pp.set_edgecolor('black') pp.set_linewidths(0.1) cmap = pg.mplviewer.cmapFromName(**kwargs) if kwargs.pop('markOutside', False): cmap.set_bad('grey') cmap.set_under('darkgrey') cmap.set_over('lightgrey') cmap.set_bad('black') pp.set_cmap(cmap) pp.set_norm(norm) pp.set_array(vals) pp.set_clim(cMin, cMax) updateAxes_(ax) cbar = kwargs.pop('colorBar', True) ori = kwargs.pop('orientation', 'horizontal') if cbar in ['horizontal', 'vertical']: ori = cbar cbar = True if cbar is True: # not for cbar=1, which is really confusing! cbar = pg.mplviewer.createColorBar(col, cMin=cMin, cMax=cMax, nLevs=5, label=label, orientation=ori) elif cbar is not False: # .. cbar is an already existing cbar .. so we update its values pg.mplviewer.updateColorBar(cbar, cMin=cMin, cMax=cMax, nLevs=5, label=label) updateAxes_(ax) return ax, cbar, ymap
def dual_half_circle(center=(0, 0), radius=1.0, sun_direction='right', ax=None, colors=('w', 'k'), **kwargs): """ Plot two half circles to a plot with the specified face colors and rotation. This is normal to use to denote the sun direction in magnetospheric science plots. Other Parameters ---------------- center : array-like, 2 elements Center in data coordinates of the circles, default (0,0) radius : float Radius of the circles, defualt 1.0 sun_direction : string or float The rotation direction of the first (white) circle. Options are ['down', 'down right', 'right', 'up left', 'up right', 'up', 'down left', 'left'] or an angle in degrees counter-clockwise from up. Default right. ax : matplotlib.axes Axis to plot the circles on. colors : array-like, 2 elements The two colors for the circle fill. The First number is the light and second is the dark. **kwargs : other keywords Other keywords to pass to matplotlib.patches.Wedge Returns ------- out : tuple Tuple of the two wedge objects Examples -------- >>> import spacepy.plot >>> spacepy.plot.dual_half_circle() """ sun_dict = { 'left': 90, 'right': -90, 'up': 0, 'down': 180, 'up right': -45, 'up left': 45, 'down right': 45 + 180, 'down left': -45 + 180, } try: angle = sun_dict[sun_direction] except KeyError: try: angle = float(sun_direction) except ValueError: raise (ValueError( "Sun_direction was not understood, must be a float or {0}". format(sun_dict.keys()))) theta1, theta2 = angle, angle + 180 if ax is None: ax = plt.gca() w1 = Wedge(center, radius, theta1, theta2, fc=colors[0], transform=ax.transData._b, **kwargs) w2 = Wedge(center, radius, theta2, theta1, fc=colors[1], transform=ax.transData._b, **kwargs) for wedge in [w1, w2]: ax.add_artist(wedge) return (w1, w2)
def plot_max_err_improving_circle(err_lst1, err_lst2, name_lst, id_lst, name, th): r_l = [] r_l = list(err_lst1) print r_l print len(r_l) print max(r_l) print min(r_l) # r = np.arange(0, 2, 0.01) n_rl = len(r_l) theta = np.deg2rad(np.arange(0, 350, 350.0 / n_rl)) r = [i / 2.0 for i in r_l] r2 = [i / 2.0 for i in err_lst2] fig = plt.figure(figsize=(14, 12)) ax = plt.subplot(111, projection='polar') # ax.scatter(theta, r, cmap='hsv', alpha=0.75) ax.set_rmax(34) ax.set_ylim(-1, 34) ax.margins(x=0, y=0) rt = np.arange(0, 34, 4) # print len(rt) ax.set_yticks(rt) # less radial ticks # ax.tick_params(axis='both',which='both',color='b') # ax.set_yticklabels(['64','56','48','40','32','24','16','8','0']) ax.set_xticks([]) ax.set_xticklabels([""]) ax.set_yticklabels([""]) tick = [0, ax.get_rmax()] print tick count = 1 len_lst = [] # for j in name_lst: # text = ax.text(1,2,'%s' % j,{'ha': 'center', 'va': 'center'},fontsize = 15) # rs = fig.canvas.get_renderer() # bb = text.get_window_extent(renderer=rs) # len_lst.append(bb.width) # text.remove() for t, j in zip(np.deg2rad(np.arange(0, 350, 350.0 / n_rl)), id_lst): # for t in name_lst: # k = len(j) ax.plot([t, t], tick, lw=0.72, color="lightgrey", zorder=2) ax.plot([t, t], [ax.get_rmax() - 0.5, ax.get_rmax()], lw=0.72, color="black", zorder=2) # if math.fmod(count,20)==0: ax.text( t, ax.get_rmax() + 0.3, '%s' % j, { 'ha': 'left', 'va': 'center' }, # transform=trans_offset, # horizontalalignment='right', # verticalalignment='bottom', rotation=t * 180 / (math.pi), fontsize=24, rotation_mode="anchor") count = count + 1 ax.annotate("", xy=(theta[-1] + 0.22, 34), xytext=(theta[-1] + 0.22, -1), arrowprops=dict(arrowstyle="->")) yl = [r'\textbf{0}', '8', '16', '24', '32', '40', '48', '56', '64'] for i, j in zip(rt, yl): ax.annotate(j, xy=(theta[-1] + 0.25, 34), xytext=(theta[-1] + 0.25, i), fontsize=14) ax.annotate('ErrBits', xy=(theta[-1] + 0.16, 30), xytext=(theta[-1] + 0.16, 28), fontsize=16, rotation=(theta[-1] + 0.22) * 180 / (math.pi), rotation_mode="anchor") print "********" print theta[-1] # ax.plot(theta, r, '--8', color='r', linewidth=1, label="Before repair",zorder=3,markersize=25,markerfacecolor="None") # ax.plot(theta, r2, '--^', color='seagreen', linewidth=1, label="After repair",zorder=3,markersize=14) ax.plot(theta, r, '-o', color='r', linewidth=1, label="Before repair", zorder=3, markersize=20) ax.plot(theta, r2, '-^', color='seagreen', linewidth=1, label="After repair", zorder=3, markersize=14) for i, j, p in zip(theta, r, r2): # # ax.scatter(i, j,marker='8', color='r',s =100,zorder=3,facecolors='none') # # ax.scatter(i, p,marker='^', color='seagreen', s =40, zorder=3) plt.plot([i, i], [j, p], linewidth=1, zorder=5, alpha=0.5, linestyle='--', color='black') # plt.arrow(i, j, 0, p-j+0.6, lw=1, zorder=5,alpha=0.5, linestyle='--') # ax.annotate("", xy=(i, p), xytext=(i, p+1), arrowprops = dict(arrowstyle="->")) # fc=fc, ec=ec, alpha=alpha, width=width, # head_width=head_width, head_length=head_length, # **arrow_params) circle1 = plt.Circle((0, 0), th / 2.0 + 1.0, color='deepskyblue', transform=ax.transData._b, fill=False, linewidth=3, zorder=2, linestyle='--', label='Repair Target') ax.add_artist(circle1) # plt.legend(handles=[circle1],bbox_to_anchor=(0.4, 0.3), prop={'size': 14}) # circle2 = plt.Circle((0, 0), 17, color='r', transform=ax.transData._b, fill=False, linewidth=3, clip_on=True, # zorder=3) # ax.add_artist(circle2) # ax.plot(theta, r,'.',color='r',markersize=14) # ax.autoscale(enable=True) # ax.axis('scaled') fn_lst = [18, 5, 4] angl_lst = [] temp_angl = 0 for i in fn_lst: temp_angl = temp_angl + (i) * 350 / (n_rl + 0.5) angl_lst.append(temp_angl) print angl_lst angl_lst[-1] = 338 temp_angl = 0 k = 0 # # color_lst = ['skyblue','azure','silver','lavender'] color_lst = ['darkorange', 'yellow', 'green'] # color_lst = ['red','red','red','red'] count = 0 weg_lst = [] print angl_lst for i in angl_lst: # ax.add_artist(Wedge((.0, .0), 35, temp_angl, i, transform=ax.transData._b,width=1,capstyle='round', fill=True, color=color_lst[k], alpha=0.5,zorder=4)) if k == 0: lb_name = str(k + 2) + "-input" else: lb_name = str(k + 2) + "-input" temp_weg = Wedge((.0, .0), 34.2, temp_angl, i, transform=ax.transData._b, width=1, fill=True, color=color_lst[k], alpha=0.5, zorder=2, label=lb_name) ax.add_artist(temp_weg) weg_lst.append(temp_weg) temp_angl = i k = k + 1 sec_legend = plt.legend(handles=weg_lst, bbox_to_anchor=(-0.03, 0.9), prop={'size': 20}) ax.add_artist(sec_legend) first_legend = plt.legend(handles=[circle1], bbox_to_anchor=(0.0, 0.08), prop={'size': 19.5}) # Add the legend manually to the current Axes. ax.add_artist(first_legend) ax.legend(bbox_to_anchor=(0.0, 0.2), prop={'size': 20}) # ax.set_yticklabels([r'\textbf{0}', '8', '16', '24', '32', '40', '48', '56', '64'], zorder=4, fontsize=20) # ax.set_yticklabels(['0','16','32','48','64']) ax.set_rlabel_position(-15) # get radial labels away from plotted line plt.savefig("graph/" + name + ".pdf", format="pdf") # ax.legend() plt.show() return 0
def roiPlot(self): sourcemap = self.binnedData.srcMaps f = fits.open(sourcemap) image_data = fits.getdata('6gev_image.fits') filename = get_pkg_data_filename('6gev_image.fits') hdu = fits.open(filename)[0] wcs = WCS(hdu.header) #Given the results of the fit, calculate the model model_data = np.zeros(f[0].shape) for source in self.sourceNames(): the_index = f.index_of(source) model_data += self._srcCnts( source)[:, None, None] * f[the_index].data[:-1, :, :] / np.sum( np.sum(f[the_index].data, axis=2), axis=1)[:-1, None, None] actual_data = np.array(self.binnedData.countsMap.data()).reshape( f[0].shape) fig = plt.figure(figsize=[14, 6]) ax = fig.add_subplot(131, projection=wcs.wcs) ax = plt.gca() c = Wedge((gc_l, gc_b), 1.0, theta1=0.0, theta2=360.0, width=14.0, edgecolor='black', facecolor='#474747', transform=ax.get_transform('galactic')) ax.add_patch(c) mappable = plt.imshow(np.sum(actual_data, axis=0), cmap='inferno', origin='lower', norm=colors.PowerNorm(gamma=0.6), vmin=0, vmax=65, interpolation='gaussian') # plt.xlabel('Galactic Longitude') plt.ylabel('Galactic Latitude') plt.title('Data') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cb = plt.colorbar(mappable, cax=cax, label='Counts per pixel') ax2 = fig.add_subplot(132, projection=wcs.wcs) ax2 = plt.gca() c2 = Wedge((gc_l, gc_b), 1.0, theta1=0.0, theta2=360.0, width=14.0, edgecolor='black', facecolor='#474747', transform=ax2.get_transform('galactic')) ax2.add_patch(c2) mappable2 = plt.imshow(np.sum(model_data, axis=0), cmap='inferno', origin='lower', norm=colors.PowerNorm(gamma=0.6), vmin=0, vmax=65, interpolation='gaussian') plt.xlabel('Galactic Longitude') plt.ylabel('Galactic Latitude') plt.title('Model') divider2 = make_axes_locatable(ax2) cax2 = divider2.append_axes("right", size="5%", pad=0.05) cb2 = plt.colorbar(mappable2, cax=cax2, label='Counts per pixel') ax3 = fig.add_subplot(133, projection=wcs.wcs) ax3 = plt.gca() c3 = Wedge((gc_l, gc_b), 1.0, theta1=0.0, theta2=360.0, width=14.0, edgecolor='black', facecolor='#474747', transform=ax3.get_transform('galactic')) ax3.add_patch(c3) mappable3 = plt.imshow(np.sum(actual_data, axis=0) - np.sum(model_data, axis=0), cmap='seismic', origin='lower', vmin=-20, vmax=20, interpolation='gaussian') # plt.xlabel('Galactic Longitude') plt.ylabel('Galactic Latitude') plt.title('Residuals') divider3 = make_axes_locatable(ax3) cax3 = divider3.append_axes("right", size="5%", pad=0.05) cb3 = plt.colorbar(mappable3, cax=cax3, label='Counts per pixel') fig.tight_layout() plt.show()
def gauge(labels=['', '', ''], colors='jet_r', arrow=1, title='', fname=False): N = 3 * len(labels) if arrow > N: raise Exception( "\n\nThe category ({}) is greated than the length\nof the labels ({})" .format(arrow, N)) if isinstance(colors, str): cmap = cm.get_cmap(colors, N) cmap = cmap(np.arange(N)) colors = cmap[::-1, :].tolist() if isinstance(colors, list): if len(colors) == N: colors = colors[::-1] else: raise Exception( "\n\nnumber of colors {} not equal to number of categories{}\n" .format(len(colors), N)) fig, ax = plt.subplots() ang_range, mid_points = degree_range(N) labels = labels[::-1] patches = [] for ang, c in zip(ang_range, colors): # sectors patches.append(Wedge((0., 0.), .4, *ang, facecolor='w', lw=2)) # arcs patches.append( Wedge((0., 0.), .4, *ang, width=0.10, facecolor=c, lw=2, alpha=0.5)) [ax.add_patch(p) for p in patches] for mid, lab in zip(mid_points, labels): ax.text(0.35 * np.cos(np.radians(mid)), 0.35 * np.sin(np.radians(mid)), lab, horizontalalignment='center', verticalalignment='center', fontsize=14, fontweight='bold', rotation=rot_text(mid)) r = Rectangle((-0.4, -0.1), 0.8, 0.1, facecolor='w', lw=2) ax.add_patch(r) ax.text(0, -0.05, title, horizontalalignment='center', verticalalignment='center', fontsize=22, fontweight='bold') pos = mid_points[abs(arrow - N)] ax.arrow(0, 0, 0.225 * np.cos(np.radians(pos)), 0.225 * np.sin(np.radians(pos)), width=0.02, head_width=0.04, head_length=0.05, fc='k', ec='k') #ax.add_patch(Circle((0, 0), radius=0.02, facecolor='k')) #ax.add_patch(Circle((0, 0), radius=0.01, facecolor='w', zorder=11)) ax.set_frame_on(False) ax.axes.set_xticks([]) ax.axes.set_yticks([]) ax.axis('equal') plt.tight_layout() if fname: fig.savefig(fname, dpi=200)
def draw(p, layout="rd"): """Draw Pharmacophore using RDKit ("rd"), OpenBabel ("ob") or spring layout ("spring") to calculate nodes positions. We recommend to use RDKit ("rd"), as it generates the clearest layouts. Args: p (Pharmacophore): model to depict layout (str, optional): layout name Returns: tuple: * matplotlib Figure * matplotlib axis """ import matplotlib.pyplot as plt from matplotlib.patches import Wedge from matplotlib.font_manager import FontManager if not isinstance(p, Pharmacophore): raise TypeError("Expected Pharmacophore, got %s instead" % type(p).__name__) if not isinstance(layout, str): raise TypeError("Invalid layout! Expected str, got %s instead." % type(layout).__name__) if p.numnodes == 0: raise ValueError("Pharmacophore is empty!") if layout == "rd": try: from decaf.toolkits.rd import layout pos = layout(p) except Exception as e: raise ImportError( "Cannot use 'rd' layout! Use 'ob' or 'spring'" "instead", e) elif layout == "ob": try: from decaf.toolkits.ob import layout pos = layout(p) except Exception as e: raise ImportError( "Cannot use 'ob' layout! Use 'rd' or 'spring'" "instead", e) elif layout == "spring": try: pos = spring_layout(p) except Exception as e: raise ImportError("Cannot use spring layout!", e) else: raise ValueError("Wrong layout specified! Use 'rd', 'ob' or 'spring'" "instead.") ax_coeff = 1. def fontsize(idx, default=FontManager.get_default_size()): coeff = p.nodes[idx]["freq"] / p.molecules size = default * coeff * ax_coeff return size fig, ax = plt.subplots() plt.axis("equal") plt.axis("off") axis = (np.min(pos[:, 0]) - 1, np.max(pos[:, 0]) + 1, np.min(pos[:, 1]) - 1, np.max(pos[:, 1]) + 1) plt.axis(axis) # calculate scaling ratio for font ax_coeff = 12. / max((axis[1] - axis[0]), (axis[3] - axis[2])) for i in range(p.numnodes): for j in range(i): if p.edges[i, j] > 0: tmp = np.array([pos[i], pos[j]]) ax.plot(tmp[:, 0], tmp[:, 1], color="#000000", zorder=1) r = p.nodes[i]["freq"] / p.molecules * 0.3 fsize = fontsize(i) nfreq = sum(p.nodes[i]["type"].values()) theta1 = 0.0 for t in p.nodes[i]["type"]: delta = 360 * p.nodes[i]["type"][t] / nfreq theta2 = theta1 + delta w = Wedge(pos[i], r, theta1, theta2, ec="none", fc=COLORS[t]) ax.add_artist(w) ax.text(pos[i][0], pos[i][1], str(p.nodes[i]["label"]), color="#000000", ha="center", va="center", size=fsize) theta1 = theta2 plt.show() return fig, ax
def _gen_axes_spines(self): path = Wedge((0, 0), 1.0, 270, 360).get_path() spine = mspines.Spine(self, 'circle', path) spine.set_patch_circle((0.5, 0.5), 0.5) return {'wedge': spine}
def Plot_Symmetry_Hist(Fraction1, Fraction2, Fraction3): origin = np.zeros(2) patches1 = [] patches2 = [] patches3 = [] opacity = 0.5 #Red theta0 = 0 thetaf = (360.0 / Fraction3.shape[0]) for i in range(0, Fraction1.shape[0]): wedge = Wedge(origin, np.mean(Fraction1[i, :]), theta0, thetaf) patches1.append(wedge) theta0 = thetaf thetaf = thetaf + (360.0 / Fraction1.shape[0]) p1 = PatchCollection(patches1, alpha=opacity) p1.set_color('#cc0000') # Green theta0 = 0 thetaf = (360.0 / Fraction3.shape[0]) for i in range(0, Fraction2.shape[0]): wedge = Wedge(origin, np.mean(Fraction2[i, :]), theta0, thetaf) patches2.append(wedge) theta0 = thetaf thetaf = thetaf + (360.0 / Fraction2.shape[0]) p2 = PatchCollection(patches2, alpha=opacity) p2.set_color('#007f00') # Necrotic theta0 = 0 thetaf = (360.0 / Fraction3.shape[0]) for i in range(0, Fraction3.shape[0]): wedge = Wedge(origin, np.mean(Fraction3[i, :]), theta0, thetaf) patches3.append(wedge) theta0 = thetaf thetaf = thetaf + (360.0 / Fraction3.shape[0]) p3 = PatchCollection(patches3, alpha=opacity) p3.set_color('#6336de') fig = plt.figure(figsize=(12, 6)) ax = fig.add_subplot(1, 2, 1) ax.set_title('Average fraction for each slice') tics = np.linspace(-0.10, 0.10, num=5) ax.set_xticks(tics) ax.set_yticks(tics) ax.set_xlim(tics[0], tics[-1]) ax.set_ylim(tics[0], tics[-1]) ax.ticklabel_format(style='sci', axis='both') p = [p1, p2, p3] Average = np.array( [np.mean(Fraction1), np.mean(Fraction2), np.mean(Fraction3)]) ind = np.argsort(Average) ax.add_collection(p[ind[2]]) ax.add_collection(p[ind[1]]) ax.add_collection(p[ind[0]]) # Label #LabelRadius = np.max(Average) + 0.01 Fraction = [Fraction1, Fraction2, Fraction3] LabelRadius = np.mean(Fraction[ind[2]], axis=1) + 0.01 LabelTheta = np.linspace((np.pi / Fraction3.shape[0]), 2 * np.pi - (np.pi / Fraction3.shape[0]), 10) LabelPosition = np.zeros((Fraction3.shape[0], 2)) LabelPosition[:, 0] = LabelRadius * np.cos(LabelTheta) LabelPosition[:, 1] = LabelRadius * np.sin(LabelTheta) Label = [] [Label.append("%i" % i) for i in range(1, Fraction3.shape[0] + 1)] for i in range(Fraction3.shape[0]): ax.text(LabelPosition[i, 0], LabelPosition[i, 1], Label[i], fontsize=12, color='gray') ax.set_aspect(1) x = np.arange(1, Fraction1.shape[0] + 1) ax2 = fig.add_subplot(3, 2, 2) ax2.errorbar(x, np.mean(Fraction1, axis=1), yerr=np.std(Fraction1, axis=1), fmt='o', color='#cc0000') #'#7a0000' # ax2.errorbar(x,np.mean(AFraction1,axis=1),yerr=np.std(Fraction1,axis=1),fmt='o',color='#a30000') # ax2.errorbar(x,np.mean(BFraction1,axis=1),yerr=np.std(Fraction1,axis=1),fmt='o',color='#cc0000') ax2.set_xticks(x) ax2.set_xlabel('Slices') ax2.set_ylabel('Fraction') ax2.ticklabel_format(style='sci', scilimits=(-2, 4), axis='y', useMathText=True) ax3 = fig.add_subplot(3, 2, 4) ax3.errorbar(x, np.mean(Fraction2, axis=1), yerr=np.std(Fraction2, axis=1), fmt='o', color='#007f00') #'#001900' # ax3.errorbar(x,np.mean(AFraction2,axis=1),yerr=np.std(Fraction2,axis=1),fmt='o',color='#004c00') # ax3.errorbar(x,np.mean(BFraction2,axis=1),yerr=np.std(Fraction2,axis=1),fmt='o',color='#007f00') ax3.set_xticks(x) ax3.set_xlabel('Slices') ax3.set_ylabel('Fraction') ax3.ticklabel_format(style='sci', scilimits=(-2, 4), axis='y', useMathText=True) ax4 = fig.add_subplot(3, 2, 6) ax4.errorbar(x, np.mean(Fraction3, axis=1), yerr=np.std(Fraction3, axis=1), fmt='o', color='#6336de') # ax4.errorbar(x,np.mean(AFraction3,axis=1),yerr=np.std(Fraction3,axis=1),fmt='o',color='#6336de') # ax4.errorbar(x,np.mean(BFraction3,axis=1),yerr=np.std(Fraction3,axis=1),fmt='o',color='#6336de') ax4.set_xticks(x) ax4.set_xlabel('Slices') ax4.set_ylabel('Fraction') ax4.ticklabel_format(style='sci', scilimits=(-2, 4), axis='y', useMathText=True) plt.subplots_adjust(wspace=0.4, hspace=0.5) plt.show()
def _gen_axes_patch(self): return Wedge((0.5, 0.5), 0.5, 270, 360)
def get_patches(self, verbose=False): """Get a list of patches for plotting via other functions.""" patches = [] if verbose: # body, color is cyan patches.append(Circle(self.loc, self.r, color='cyan')) # ground sensor patches.append(Circle(self.loc, 0.4, color='gray')) # comm unit patches.append(Circle(self.loc, 0.2, color='green')) # IR sensors for i in range(len(self.ir_ang)): # width and height of the rectangular IR sensor representation width = 0.2 height = 0.5 placement_ang = norm_ang(self.ir_placement[i] + self.ang) detect_ang = norm_ang(self.ir_ang[i] + self.ang) loc = find_loc(self.loc, placement_ang, self.r - 0.3) patches.append( Rectangle((loc[0], loc[1]), width / 2, height / 2, angle=detect_ang, color='black')) patches.append( Rectangle((loc[0], loc[1]), height / 2, width / 2, angle=detect_ang + 90, color='black')) patches.append( Rectangle((loc[0], loc[1]), width / 2, height / 2, angle=detect_ang + 180, color='black')) patches.append( Rectangle((loc[0], loc[1]), height / 2, width / 2, angle=detect_ang + 270, color='black')) # easier but uglier to use Ellipses; abandoned # ax.add_patch(Ellipse(loc, 0.2, 0.7, # angle=detect_ang, color='black')) patches.append( FancyArrow(loc[0], loc[1], find_dx(loc[0], detect_ang, 0.5), find_dy(loc[1], detect_ang, 0.5), color='black', length_includes_head=False, head_width=0.15)) # comm sensors comm_sensors = self.comm_sensors # use different, random color to distinguish between the 4 sensors for comm_range in comm_sensors: patches.append( Wedge(self.loc, 0.8, norm_ang(comm_range[0] + self.ang), norm_ang(comm_range[1] + self.ang), 0.3, color=(rd.uniform(0, 1), rd.uniform(0, 1), rd.uniform(0, 1)))) # wheels left_ang = norm_ang(self.ang + 90) right_ang = norm_ang(self.ang - 90) left_center = find_loc(self.loc, left_ang, self.r - 0.4) right_center = find_loc(self.loc, right_ang, self.r - 0.4) # wheels are represented with a ellipse # width=0.3, length=1.5 patches.append( Ellipse(left_center, 0.3, 1.5, left_ang, color='red')) patches.append( Ellipse(right_center, 0.3, 1.5, right_ang, color='red')) # add mid line patches.append( FancyArrow(self.loc[0], self.loc[1], find_dx(self.loc[0], self.ang, self.r), find_dy(self.loc[1], self.ang, self.r), color='black', length_includes_head=True, head_width=0.2)) else: # body; color is as assigned patches.append(Circle(self.loc, self.r, color=self.color)) # add a longer mid line for better display in the environment patches.append( FancyArrow(self.loc[0], self.loc[1], find_dx(self.loc[0], self.ang, 15), find_dy(self.loc[1], self.ang, 15), color='black', length_includes_head=True, head_width=6)) return patches
def wedge_from_sector_(s : KrSector, rmax : float =200, scale : float =0.1) ->Wedge: w = Wedge((0.5, 0.5), scale*s.rmax/rmax, s.phimin, s.phimax, width=scale*(s.rmax - s.rmin)/rmax) return w
def plot( self, fig=None, is_lam_only=False, sym=1, alpha=0, delta=0, is_edge_only=False ): """Plot the Lamination in a matplotlib fig Parameters ---------- self : LamSquirrelCage A LamSquirrelCage object fig : if None, open a new fig and plot, else add to the current one (Default value = None) is_lam_only : bool True to plot only the lamination (remove the bare) sym : int Symmetry factor (1= full machine, 2= half of the machine...) alpha : float Angle for rotation [rad] delta : complex Complex value for translation is_edge_only: bool To plot transparent Patches Returns ------- None """ # Lamination and ventilation ducts patches (fig, axes, patch_leg, label_leg) = init_fig(fig) # Plot the lamination super(type(self), self).plot( fig, is_lam_only=is_lam_only, sym=sym, alpha=alpha, delta=delta, is_edge_only=is_edge_only, ) # Plot the winding if needed if not is_lam_only: # point needed to plot the bar of a slot Hbar = self.winding.conductor.Hbar Wbar = self.winding.conductor.Wbar if self.is_internal: HS = self.Rext - self.slot.comp_height() Bar_points = [ HS + 1j * Wbar / 2, HS - 1j * Wbar / 2, HS + Hbar - 1j * Wbar / 2, HS + Hbar + 1j * Wbar / 2, ] else: HS = self.Rint + self.slot.comp_height() Bar_points = [ HS + 1j * Wbar / 2, HS - 1j * Wbar / 2, HS - Hbar - 1j * Wbar / 2, HS - Hbar + 1j * Wbar / 2, ] Bar_array = array(Bar_points) # Computation of the coordinate of every bar by complex rotation bar_list = [] for i in range(self.slot.Zs): bar_list.append(Bar_array * exp(-1j * i * (2 * pi) / self.slot.Zs)) patches = list() # Creation of the bar patches for wind in bar_list: patches.append(Polygon(list(zip(wind.real, wind.imag)), color=BAR_COLOR)) # Add the Short Circuit Ring Rmw = self.slot.comp_radius_mid_wind() patches.append( Wedge( (0, 0), Rmw + self.Hscr / 2.0, 0, 360, width=self.Hscr, color=SCR_COLOR ) ) # Full ring # Display the result axes.set_xlabel("(m)") axes.set_ylabel("(m)") axes.set_title("Squirrel Cage Rotor") # Axis Setup axis("equal") Lim = self.Rext * 1.5 axes.set_xlim(-Lim, Lim) axes.set_ylim(-Lim, Lim) if not is_lam_only: # Add the bare to the fig for patch in patches: axes.add_patch(patch) # Legend setup (Rotor already setup by LamSlotWind.plot) if "Rotor Bar" not in label_leg: patch_leg.append(Patch(color=BAR_COLOR)) label_leg.append("Rotor Bar") if "Short Circuit Ring" not in label_leg: patch_leg.append(Patch(color=SCR_COLOR)) label_leg.append("Short Circuit Ring") legend(patch_leg, label_leg) fig.show()
def sim_animation(lifetime, limits, walls, trees, agents): # defs fig = plt.figure() ax = plt.axes(xlim=(0, limits[0]), ylim=(0, limits[1]), aspect="equal") ax.grid = True # for time time = ax.text(limits[0] / 2, limits[1] + 10, str("time: 0"), ha="left", va="top") # plot basics for agents agent_objs = [] o_lines = [] olf_domain = [] aud_domain = [] vis_domain = [] feed_domain = [] # agent objects for agent in agents: # create objects # agent ag = plt.Circle((agent.positions[0][0], agent.positions[0][1]), radius=agent.r, color="blue", fill=True) agent_objs.append(ag) # orientation line o_line, = plt.plot([], [], color="orange") o_lines.append(o_line) # olfactory domain olf = Wedge((0, 0), r=agent.genotype.olf_range, theta1=0, theta2=0, color="purple", fill=False, visible=True) olf_domain.append(olf) # auditory domain aud_left = plt.Circle((0, 0), radius=agent.genotype.aud_range, color="red", fill=False, visible=False) aud_right = plt.Circle((0, 0), radius=agent.genotype.aud_range, color="red", fill=False, visible=False) aud_domain.append([aud_left, aud_right]) # visual domain ir_left = Wedge((0, 0), r=agent.genotype.ray_length, theta1=0, theta2=0, color="grey", fill=False, visible=True) ir_right = Wedge((0, 0), r=agent.genotype.ray_length, theta1=0, theta2=0, color="grey", fill=False, visible=True) vis_domain.append([ir_left, ir_right]) # feeding domain feed = plt.Circle((0, 0), radius=(agent.feed_range + agent.r), color="green", fill=False, visible=False) feed_domain.append(feed) def init(): # optional walls for wall in walls: ax.plot([wall.xmin, wall.xmax], [wall.ymin, wall.ymax], color="black") # trees for tree in trees: t = plt.Circle((tree.x, tree.y), radius=tree.r, color="green", fill="True") ax.add_patch(t) # agents and sensors (not necessary for orientation) for agent in agent_objs: ax.add_patch(agent) for olf in olf_domain: ax.add_patch(olf) for aud in aud_domain: for audx in aud: ax.add_patch(audx) for ir in vis_domain: for irx in ir: ax.add_patch(irx) for feed in feed_domain: ax.add_patch(feed) return agent, olf, audx, irx, feed, def animate(i): # time time.set_text("time: " + str(i)) # for each agent in the list of animated objects for enum, agent_obj in enumerate(agent_objs): # location data o = np.degrees(agents[enum].positions[i][2]) x = agents[enum].positions[i][0] y = agents[enum].positions[i][1] # agent body (circle) agent_obj.center = (x, y) agent_obj.set_color("blue") # agent orientation (line from center) ox = x + agents[enum].r * np.cos(np.radians(o)) oy = y + agents[enum].r * np.sin(np.radians(o)) o_lines[enum].set_data([x, ox], [y, oy]) # olf domain (wedge) olf_x = x + agents[enum].r * np.cos(np.radians(o)) olf_y = y + agents[enum].r * np.sin(np.radians(o)) olf_o1 = geometry.force_angle_degrees( np.degrees(agents[enum].sensors.olf_angles[0]) + o) olf_o2 = geometry.force_angle_degrees( np.degrees(agents[enum].sensors.olf_angles[1]) + o) olf_domain[enum].center = (olf_x, olf_y) olf_domain[enum].theta1 = olf_o1 olf_domain[enum].theta2 = olf_o2 olf_domain[enum]._recompute_path() # olf signals olf_val = agents[enum].states[i][2] print("time: {}, location: {},{}, agent: {}, olf_val: {}".format( i, round(x, 2), round(y, 2), enum, olf_val)) if olf_val > 0: # olf_domain[enum].set_visible(True) olf_domain[enum].set_color("purple") else: # olf_domain[enum].set_visible(False) olf_domain[enum].set_color("grey") # aud domain (circles) for n in range(len(aud_domain[enum])): #aud_o = o + agents[enum].ps[5][n] aud_o = o + agents[enum].sensors.aud_angles[n] aud_x = x + agents[enum].r * np.cos(aud_o) aud_y = y + agents[enum].r * np.sin(aud_o) aud_domain[enum][n].center = (aud_x, aud_y) # auditory signal aud_val = agents[enum].states[i][3 + n] # if aud_val > 0: # aud_domain[enum][n].set_visible(True) # else: # aud_domain[enum][n].set_visible(False) # vis domain (wedges) for n in range(len(vis_domain[enum])): # vis_or = agent_or + agent.sensor_or[n], ps[1]: ir_angles: [rad(-60), rad(60)] vis_o = geometry.force_angle(agents[enum].positions[i][2] + agents[enum].sensors.ir_angles[n]) # sensor location vis_x = x + agents[enum].r * np.cos(vis_o) vis_y = y + agents[enum].r * np.sin(vis_o) # beam_spread, start and end angles of beam vis_sp = agents[enum].genotype.beam_spread / 2 vis_o1 = geometry.force_angle_degrees( np.degrees(vis_o) - vis_sp) vis_o2 = geometry.force_angle_degrees( np.degrees(vis_o) + vis_sp) vis_domain[enum][n].center = (vis_x, vis_y) vis_domain[enum][n].theta1 = vis_o1 vis_domain[enum][n].theta2 = vis_o2 vis_domain[enum][n]._recompute_path() # visual signals vis_val = agents[enum].states[i][n] # print("time: {}, location: {},{}, agent: {}, sensor: {}, vis_val: {}".format(i,round(x,2),round(y,2),enum,n,vis_val)) if vis_val > 0: # vis_domain[enum][n].set_visible(True) vis_domain[enum][n].set_color("yellow") else: # vis_domain[enum][n].set_visible(False) vis_domain[enum][n].set_color("grey") # feeding (circle) if agents[enum].feeding_states[i] == True: feed.center = (x, y) feed.set_visible(True) else: feed.set_visible(False) # check energy values (circle) energy = agents[enum].states[i][5] if 0 < energy <= 200: agent_obj.set_color("grey") agent_obj.fill = False if energy <= 0: agent_obj.set_color("black") agent_obj.fill = False olf_domain[enum].set_visible(False) aud_domain[enum][0].set_visible = False aud_domain[enum][1].set_visible = False vis_domain[enum][0].set_visible(False) vis_domain[enum][1].set_visible(False) all_aud = [aud for audx in aud_domain for aud in audx] all_vis = [vis for visx in vis_domain for vis in visx] return time, tuple(agent_objs) + tuple(o_lines) + tuple( olf_domain) + tuple(all_aud) + tuple(all_vis) + tuple(feed_domain) anim = animation.FuncAnimation(fig, animate, init_func=init, frames=lifetime, interval=200, blit=False) plt.show()
def draw_plot(player, season, template, table): mffw_cols = [ 'npxG', 'npxG/Sh', 'PrgRatio', 'KP', 'xA', 'Prog', 'Final3rdDrib', 'Press' ] mffw_colors = [ 'red', 'red', 'blue', 'blue', 'blue', 'yellow', 'yellow', 'green' ] fw_cols = [ 'npxG', 'npxG/Sh', 'SoT%', 'Sh/90', 'Passes', 'xA', 'Prog', 'Press' ] fw_colors = ['red', 'red', 'red', 'red', 'blue', 'blue', 'yellow', 'green'] mf_cols = [ 'npxG', 'xA', 'PrgRatio', 'Passes', 'Prog', 'PrgRatioDrib', 'Tkl', 'Press' ] mf_colors = [ 'red', 'blue', 'blue', 'blue', 'yellow', 'yellow', 'green', 'green' ] df_cols = ['xA', 'CrsPA', 'Prog', 'Blocks', 'Int', 'Tkl%', 'Press', 'Err'] df_colors = [ 'blue', 'blue', 'yellow', 'green', 'green', 'green', 'green', 'green' ] dfmf_cols = [ 'xA', 'CrsPA', 'PrgRatio', 'Passes', 'Prog', 'Int', 'Tkl%', 'Press' ] dfmf_colors = [ 'blue', 'blue', 'blue', 'blue', 'yellow', 'green', 'green', 'green' ] dffw_cols = ['npxG', 'xA', 'CrsPA', 'KP', '#Pl', 'Prog', 'Tkl', 'Press'] dffw_colors = [ 'red', 'blue', 'blue', 'blue', 'yellow', 'yellow', 'green', 'green' ] if template == 'FW': cols = fw_cols colors = fw_colors elif template == 'MFFW' or template == 'FWMF': cols = mffw_cols colors = mffw_colors elif template == 'MF': cols = mf_cols colors = mf_colors elif template == 'DF': cols = df_cols colors = df_colors elif template == 'DFMF': cols = dfmf_cols colors = dfmf_colors elif template == 'DFFW' or template == 'FWDF': cols = dffw_cols colors = dffw_colors label_coords = [(0.9, 0.65), (0.65, 0.9), (0.30, 0.9), (0.01, 0.65), (0.01, 0.35), (0.30, 0.075), (0.65, 0.075), (0.9, 0.35)] fig, axes = plt.subplots(2, 3, figsize=(30, 20)) for i in range(2): for j in range(3): if i == 0: player = table['Player'][table.index[j]] season = table['Season'][table.index[j]] else: player = table['Player'][table.index[j + 3]] season = table['Season'][table.index[j + 3]] player_stats = players[(players['Player'] == player) & (players['Season'] == season)] player_stats = player_stats[cols] maxs = mod_players[cols].max() player_viz = [] for col in cols: player_viz.append(player_stats[col][player_stats.index[0]] / maxs[col]) for n in range(8): axes[i, j].add_patch( Wedge((0.5, 0.5), player_viz[n] * 0.4, 45 * n, 45 * (n + 1), edgecolor='black', facecolor=colors[n])) axes[i, j].annotate(cols[n], label_coords[n], fontsize=16) draw_circle = plt.Circle((0.5, 0.5), 0.4, fill=False) axes[i, j].add_artist(draw_circle) axes[i, j].axis('off') axes[i, j].set_title(f'{player}, {season-1}/{season-2000}', fontsize=24) plt.show() return fig
parameters["electrodeWidth"], angle=angle, fc=col, ec=col, zorder=-1, )) elif parameters["geometry"] == "circle": electrodeWidth = (parameters["electrodeWidth"] / (parameters["radius"] * 2 * np.pi) * 360 ) # in degrees ax.add_artist( Wedge( (0, 0), parameters["radius"] + electodePlotWidth / 2, electrodes[i][0] - electrodeWidth / 2, electrodes[i][0] + electrodeWidth / 2, width=electodePlotWidth, fc=col, ec=col, zorder=-1, )) ax.scatter(acceptorPos[:, 0], acceptorPos[:, 1], c="k", marker=".", s=20) ax.scatter(donorPos[:, 0], donorPos[:, 1], c="k", marker="x", s=20) for l in range(len(electrodes)): trajectories = trajectoriesSortedByStartEnd[k][l]
def add_sweep(self, center, r, theta1, theta2, width=None, **kwargs): self.patches.append( Wedge(center, r, theta1, theta2, width=width, **kwargs))
if k == 0: # lb_name = u' '.join((str(k + 1), "输入变量")).encode('utf-8').strip() # lb_name = smart_str(str(k + 1) + u"输入变量") lb_name = str(k + 1) + "-input" else: # lb_name = u' '.join((str(k + 1), "输入变量")).encode('utf-8').strip() # lb_name = smart_str(str(k + 1) + u"输入变量") lb_name = str(k + 1) + "-input" print lb_name print type(lb_name) temp_weg = Wedge((.0, .0), 34.2, temp_angl, i, transform=ax.transData._b, width=1, fill=True, color=color_lst[k], alpha=0.5, zorder=2, label=lb_name) ax.add_artist(temp_weg) weg_lst.append(temp_weg) temp_angl = i k = k + 1 # size = 0.4 # cmap = plt.get_cmap("tab20c") # outer_colors = cmap(np.arange(3)*4) # inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10])) #
def plot(network, margin=0.05, ax=None, geomap=True, projection=None, bus_colors='b', line_colors={ 'Line': 'g', 'Link': 'cyan' }, bus_sizes=10, line_widths={ 'Line': 2, 'Link': 2 }, flow=None, layouter=None, title="", line_cmap=None, bus_cmap=None, boundaries=None, geometry=False, branch_components=['Line', 'Link'], jitter=None, basemap=None, basemap_parameters=None, color_geomap=None): """ Plot the network buses and lines using matplotlib and cartopy/basemap. Parameters ---------- margin : float Margin at the sides as proportion of distance between max/min x,y ax : matplotlib ax, defaults to plt.gca() Axis to which to plot the network geomap: bool/str, default True Switch to use Basemap or Cartopy (depends on what is installed). If string is passed, it will be used as a resolution argument. For Basemap users 'c' (crude), 'l' (low), 'i' (intermediate), 'h' (high), 'f' (full) are valid resolutions options. For Cartopy users '10m', '50m', '110m' are valid resolutions options. projection: cartopy.crs.Projection, defaults to None Define the projection of your geomap, only valid if cartopy is installed. If None (default) is passed the projection for cartopy is set to cartopy.crs.PlateCarree bus_colors : dict/pandas.Series Colors for the buses, defaults to "b" bus_sizes : dict/pandas.Series Sizes of bus points, defaults to 10 line_colors : dict/pandas.Series Colors for the lines, defaults to "g" for Lines and "cyan" for Links. Colors for branches other than Lines can be specified using a pandas Series with a MultiIndex. line_widths : dict/pandas.Series Widths of lines, defaults to 2. Widths for branches other than Lines can be specified using a pandas Series with a MultiIndex. flow : snapshot/pandas.Series/function/string Flow to be displayed in the plot, defaults to None. If an element of network.snapshots is given, the flow at this timestamp will be displayed. If an aggregation function is given, is will be applied to the total network flow via pandas.DataFrame.agg (accepts also function names). Otherwise flows can be specified by passing a pandas Series with MultiIndex including all necessary branch components. Use the line_widths argument to additionally adjust the size of the flow arrows. layouter : networkx.drawing.layout function, default None Layouting function from `networkx <https://networkx.github.io/>`_ which overrules coordinates given in ``network.buses[['x','y']]``. See `list <https://networkx.github.io/documentation/stable/reference/drawing.html#module-networkx.drawing.layout>`_ of available options. title : string Graph title line_cmap : plt.cm.ColorMap/str|dict If line_colors are floats, this color map will assign the colors. Use a dict to specify colormaps for more than one branch type. bus_cmap : plt.cm.ColorMap/str If bus_colors are floats, this color map will assign the colors boundaries : list of four floats Boundaries of the plot in format [x1,x2,y1,y2] branch_components : list of str Branch components to be plotted, defaults to Line and Link. jitter : None|float Amount of random noise to add to bus positions to distinguish overlapping buses basemap_parameters : dict Specify a dict with additional constructor parameters for the Basemap. Will disable Cartopy. Use this feature to set a custom projection. (e.g. `{'projection': 'tmerc', 'lon_0':10.0, 'lat_0':50.0}`) color_geomap : dict or bool Specify colors to paint land and sea areas in. If True, it defaults to `{'ocean': 'lightblue', 'land': 'whitesmoke'}`. If no dictionary is provided, colors are white. Returns ------- bus_collection, branch_collection1, ... : tuple of Collections Collections for buses and branches. """ defaults_for_branches = pd.Series({ 'Link': dict(color="cyan", width=2), 'Line': dict(color="b", width=2), 'Transformer': dict(color='green', width=2) }).rename_axis('component') if not plt_present: logger.error("Matplotlib is not present, so plotting won't work.") return if basemap is not None: logger.warning("argument `basemap` is deprecated, " "use `geomap` instead.") geomap = basemap if geomap: if not (cartopy_present or basemap_present): # Not suggesting Basemap since it is being deprecated logger.warning( "Cartopy needs to be installed to use `geomap=True`.") geomap = False # Use cartopy by default, fall back on basemap use_basemap = False use_cartopy = cartopy_present if not use_cartopy: use_basemap = basemap_present # If the user specifies basemap parameters, they prefer # basemap over cartopy. # (This means that you can force the use of basemap by # setting `basemap_parameters={}`) if basemap_present: if basemap_parameters is not None: logger.warning("Basemap is being deprecated, consider " "switching to Cartopy.") use_basemap = True use_cartopy = False if use_cartopy: if projection is None: projection = get_projection_from_crs(network.srid) if ax is None: ax = plt.gca(projection=projection) else: assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot), ( 'The passed axis is not a GeoAxesSubplot. You can ' 'create one with: \nimport cartopy.crs as ccrs \n' 'fig, ax = plt.subplots(' 'subplot_kw={"projection":ccrs.PlateCarree()})') elif ax is None: ax = plt.gca() x, y = _get_coordinates(network, layouter=layouter) axis_transform = ax.transData if geomap: if use_cartopy: axis_transform = draw_map_cartopy(network, x, y, ax, boundaries, margin, geomap, color_geomap) new_coords = pd.DataFrame(ax.projection.transform_points( axis_transform, x.values, y.values), index=network.buses.index, columns=['x', 'y', 'z']) x, y = new_coords['x'], new_coords['y'] elif use_basemap: basemap_transform = draw_map_basemap(network, x, y, ax, boundaries, margin, geomap, basemap_parameters, color_geomap) # A non-standard projection might be used; the easiest way to # support this is to tranform the bus coordinates. x, y = basemap_transform(x.values, y.values) x = pd.Series(x, network.buses.index) y = pd.Series(y, network.buses.index) if jitter is not None: x = x + np.random.uniform(low=-jitter, high=jitter, size=len(x)) y = y + np.random.uniform(low=-jitter, high=jitter, size=len(y)) if isinstance(bus_sizes, pd.Series) and isinstance(bus_sizes.index, pd.MultiIndex): # We are drawing pies to show all the different shares assert len(bus_sizes.index.levels[0].difference(network.buses.index)) == 0, \ "The first MultiIndex level of bus_sizes must contain buses" assert (isinstance(bus_colors, dict) and set(bus_colors).issuperset(bus_sizes.index.levels[1])), \ "bus_colors must be a dictionary defining a color for each element " \ "in the second MultiIndex level of bus_sizes" bus_sizes = bus_sizes.sort_index(level=0, sort_remaining=False) if geomap: bus_sizes *= projected_area_factor(ax, network.srid)**2 patches = [] for b_i in bus_sizes.index.levels[0]: s = bus_sizes.loc[b_i] radius = s.sum()**0.5 if radius == 0.0: ratios = s else: ratios = s / s.sum() start = 0.25 for i, ratio in ratios.iteritems(): patches.append( Wedge((x.at[b_i], y.at[b_i]), radius, 360 * start, 360 * (start + ratio), facecolor=bus_colors[i])) start += ratio bus_collection = PatchCollection(patches, match_original=True) ax.add_collection(bus_collection) else: c = pd.Series(bus_colors, index=network.buses.index) s = pd.Series(bus_sizes, index=network.buses.index, dtype="float").fillna(10) bus_collection = ax.scatter(x, y, c=c, s=s, cmap=bus_cmap, edgecolor='face') def as_branch_series(ser): # ensure that this function always return a multiindexed series if isinstance(ser, dict) and set(ser).issubset(branch_components): return pd.concat( { c.name: pd.Series(s, index=c.df.index) for c, s in zip(network.iterate_components(ser.keys()), ser.values()) }, names=['component', 'name']) elif isinstance(ser, pd.Series) and isinstance(ser.index, pd.MultiIndex): return ser.rename_axis(index=['component', 'name']) else: ser = pd.Series(ser, network.lines.index) return pd.concat([ser], axis=0, keys=['Line'], names=['component', 'name']).fillna(0) line_colors = as_branch_series(line_colors) line_widths = as_branch_series(line_widths) if not isinstance(line_cmap, dict): line_cmap = {'Line': line_cmap} branch_collections = [] if flow is not None: flow = (_flow_ds_from_arg( flow, network, branch_components).pipe(as_branch_series).div( sum( len(t.df) for t in network.iterate_components(branch_components)) + 100)) flow = flow.mul(line_widths[flow.index], fill_value=1) # update the line width, allows to set line widths separately from flows line_widths.update((5 * flow.abs()).pipe(np.sqrt)) arrows = directed_flow(network, flow, x=x, y=y, ax=ax, geomap=geomap, branch_colors=line_colors, branch_comps=branch_components, cmap=line_cmap['Line']) branch_collections.append(arrows) for c in network.iterate_components(branch_components): l_defaults = defaults_for_branches[c.name] l_widths = line_widths.get(c.name, l_defaults['width']) l_nums = None l_colors = line_colors.get(c.name, l_defaults['color']) if isinstance(l_colors, pd.Series): if issubclass(l_colors.dtype.type, np.number): l_nums = l_colors l_colors = None else: l_colors.fillna(l_defaults['color'], inplace=True) if not geometry: segments = (np.asarray( ((c.df.bus0.map(x), c.df.bus0.map(y)), (c.df.bus1.map(x), c.df.bus1.map(y)))).transpose(2, 0, 1)) else: from shapely.wkt import loads from shapely.geometry import LineString linestrings = c.df.geometry[lambda ds: ds != ''].map(loads) assert all(isinstance(ls, LineString) for ls in linestrings), ( "The WKT-encoded geometry in the 'geometry' column must be " "composed of LineStrings") segments = np.asarray(list(linestrings.map(np.asarray))) l_collection = LineCollection(segments, linewidths=l_widths, antialiaseds=(1, ), colors=l_colors, transOffset=ax.transData) if l_nums is not None: l_collection.set_array(np.asarray(l_nums)) l_collection.set_cmap(line_cmap.get(c.name, None)) l_collection.autoscale() ax.add_collection(l_collection) l_collection.set_zorder(3) branch_collections.append(l_collection) bus_collection.set_zorder(4) ax.update_datalim(compute_bbox_with_margins(margin, x, y)) ax.autoscale_view() if geomap: if use_cartopy: ax.outline_patch.set_visible(False) ax.axis('off') ax.set_title(title) return (bus_collection, ) + tuple(branch_collections)
def plot(network, margin=0.05, ax=None, basemap=True, bus_colors='b', line_colors='g', bus_sizes=10, line_widths=2, title="", line_cmap=None, bus_cmap=None, boundaries=None, geometry=False, branch_components=['Line', 'Link'], jitter=None): """ Plot the network buses and lines using matplotlib and Basemap. Parameters ---------- margin : float Margin at the sides as proportion of distance between max/min x,y ax : matplotlib ax, defaults to plt.gca() Axis to which to plot the network basemap : bool, default True Switch to use Basemap bus_colors : dict/pandas.Series Colors for the buses, defaults to "b" bus_sizes : dict/pandas.Series Sizes of bus points, defaults to 10 line_colors : dict/pandas.Series Colors for the lines, defaults to "g" for Lines and "cyan" for Links. Colors for branches other than Lines can be specified using a pandas Series with a MultiIndex. line_widths : dict/pandas.Series Widths of lines, defaults to 2. Widths for branches other than Lines can be specified using a pandas Series with a MultiIndex. title : string Graph title line_cmap : plt.cm.ColorMap/str|dict If line_colors are floats, this color map will assign the colors. Use a dict to specify colormaps for more than one branch type. bus_cmap : plt.cm.ColorMap/str If bus_colors are floats, this color map will assign the colors boundaries : list of four floats Boundaries of the plot in format [x1,x2,y1,y2] branch_components : list of str Branch components to be plotted, defaults to Line and Link. jitter : None|float Amount of random noise to add to bus positions to distinguish overlapping buses Returns ------- bus_collection, branch_collection1, ... : tuple of Collections Collections for buses and branches. """ defaults_for_branches = { 'Link': dict(color="cyan", width=2), 'Line': dict(color="b", width=2), 'Transformer': dict(color='green', width=2) } if not plt_present: logger.error("Matplotlib is not present, so plotting won't work.") return if ax is None: ax = plt.gca() def compute_bbox_with_margins(margin, x, y): #set margins pos = np.asarray((x, y)) minxy, maxxy = pos.min(axis=1), pos.max(axis=1) xy1 = minxy - margin*(maxxy - minxy) xy2 = maxxy + margin*(maxxy - minxy) return tuple(xy1), tuple(xy2) x = network.buses["x"] y = network.buses["y"] if jitter is not None: x = x + np.random.uniform(low=-jitter, high=jitter, size=len(x)) y = y + np.random.uniform(low=-jitter, high=jitter, size=len(y)) if basemap and basemap_present: if boundaries is None: (x1, y1), (x2, y2) = compute_bbox_with_margins(margin, x, y) else: x1, x2, y1, y2 = boundaries bmap = Basemap(resolution='l', epsg=network.srid, llcrnrlat=y1, urcrnrlat=y2, llcrnrlon=x1, urcrnrlon=x2, ax=ax) bmap.drawcountries() bmap.drawcoastlines() x, y = bmap(x.values, y.values) x = pd.Series(x, network.buses.index) y = pd.Series(y, network.buses.index) if isinstance(bus_sizes, pd.Series) and isinstance(bus_sizes.index, pd.MultiIndex): # We are drawing pies to show all the different shares assert len(bus_sizes.index.levels[0].difference(network.buses.index)) == 0, \ "The first MultiIndex level of bus_sizes must contain buses" assert isinstance(bus_colors, dict) and set(bus_colors).issuperset(bus_sizes.index.levels[1]), \ "bus_colors must be a dictionary defining a color for each element " \ "in the second MultiIndex level of bus_sizes" bus_sizes = bus_sizes.sort_index(level=0, sort_remaining=False) patches = [] for b_i in bus_sizes.index.levels[0]: s = bus_sizes.loc[b_i] radius = s.sum()**0.5 ratios = s/s.sum() start = 0.25 for i, ratio in ratios.iteritems(): patches.append(Wedge((x.at[b_i], y.at[b_i]), radius, 360*start, 360*(start+ratio), facecolor=bus_colors[i])) start += ratio bus_collection = PatchCollection(patches, match_original=True) ax.add_collection(bus_collection) else: c = pd.Series(bus_colors, index=network.buses.index) if c.dtype == np.dtype('O'): c.fillna("b", inplace=True) c = list(c.values) s = pd.Series(bus_sizes, index=network.buses.index, dtype="float").fillna(10) bus_collection = ax.scatter(x, y, c=c, s=s, cmap=bus_cmap) def as_branch_series(ser): if isinstance(ser, dict) and set(ser).issubset(branch_components): return pd.Series(ser) elif isinstance(ser, pd.Series): if isinstance(ser.index, pd.MultiIndex): return ser index = ser.index ser = ser.values else: index = network.lines.index return pd.Series(ser, index=pd.MultiIndex(levels=(["Line"], index), labels=(np.zeros(len(index)), np.arange(len(index))))) line_colors = as_branch_series(line_colors) line_widths = as_branch_series(line_widths) if not isinstance(line_cmap, dict): line_cmap = {'Line': line_cmap} branch_collections = [] for c in network.iterate_components(branch_components): l_defaults = defaults_for_branches[c.name] l_widths = line_widths.get(c.name, l_defaults['width']) l_nums = None l_colors = line_colors.get(c.name, l_defaults['color']) if isinstance(l_colors, pd.Series): if issubclass(l_colors.dtype.type, np.number): l_nums = l_colors l_colors = None else: l_colors.fillna(l_defaults['color'], inplace=True) if not geometry: segments = (np.asarray(((c.df.bus0.map(x), c.df.bus0.map(y)), (c.df.bus1.map(x), c.df.bus1.map(y)))) .transpose(2, 0, 1)) else: from shapely.wkt import loads from shapely.geometry import LineString linestrings = c.df.geometry.map(loads) assert all(isinstance(ls, LineString) for ls in linestrings), \ "The WKT-encoded geometry in the 'geometry' column must be composed of LineStrings" segments = np.asarray(list(linestrings.map(np.asarray))) if basemap and basemap_present: segments = np.transpose(bmap(*np.transpose(segments, (2, 0, 1))), (1, 2, 0)) l_collection = LineCollection(segments, linewidths=l_widths, antialiaseds=(1,), colors=l_colors, transOffset=ax.transData) if l_nums is not None: l_collection.set_array(np.asarray(l_nums)) l_collection.set_cmap(line_cmap.get(c.name, None)) l_collection.autoscale() ax.add_collection(l_collection) l_collection.set_zorder(1) branch_collections.append(l_collection) bus_collection.set_zorder(2) ax.update_datalim(compute_bbox_with_margins(margin, x, y)) ax.autoscale_view() ax.set_title(title) return (bus_collection,) + tuple(branch_collections)
result.loc[j, 'Ln'] = round(ln, 2) result.loc[j, 'Ln/Dn'] = round(ld, 2) result.loc[j, 'influence_degree'] = round(influence_degree, 2) result.loc[j, 'azimuth'] = round(azimuth, 2) result.loc[j, 'influence_sector'] = str(influence_sector) # 转为str存入防止数据类型异常报错 influence_sectors = influence_sectors.union(influence_sector) # 机位影响扇区 free_sectors = I.closed(0, 360) - influence_sectors # 测试扇区 result.loc[i, 'influence_sectors'] = str(influence_sectors) result.loc[i, 'freeflow_sectors'] = str(free_sectors) site_info.loc[i, 'influence_sectors'] = str(influence_sectors) # site_info最终存入'Summary'的sheet site_info.loc[i, 'freeflow_sectors'] = str(free_sectors) radii = 2 * site_info['rotor diameter(m)'][i] for sector_wake in list(influence_sectors): theta1 = 90 - sector_wake.lower # 调整到笛卡尔坐标系的画图方向 theta2 = 90 - sector_wake.upper wedge = Wedge((site_info['X(m)'][i], site_info['Y(m)'][i]), radii, theta2, theta1) wake_patches_all.append(wedge) wake_patches.append(wedge) for sector_free in list(free_sectors): theta1 = 90 - sector_free.lower theta2 = 90 - sector_free.upper wedge = Wedge((site_info['X(m)'][i], site_info['Y(m)'][i]), radii, theta2, theta1) free_patches_all.append(wedge) free_patches.append(wedge) result.to_excel(writer, sheet_name='WTG{}'.format(site_info['LABEL'][i]), startrow=0, startcol=0, index=False) """【单机位点】尾流影响扇区/测试扇区示意图绘制""" wedges_display.wedgeplt(site_info['X(m)'], site_info['Y(m)'], site_info['LABEL'], site_info['X(m)'][i], site_info['Y(m)'][i], site_info['rotor diameter(m)'][i], site_info['LABEL'][i], wake_patches, 'wake-influenced', output_path)
def me_item(pos): r = Wedge(pos, .3, 0, 320, facecolor="#fa9420") plt.gca().add_patch(r)
y_cood[i] = lidar_dep[i] * np.sin(lidar_deg[i]) return x_cood, y_cood # print lidar_np.shape for i, txtname in enumerate(sorted(glob.iglob('*.txt'))): x, y = scancoodtrans(txtname) x_label, y_label = x[30:150], y[30:150] plt.figure(i) #scan range circle = plt.Circle((0, 0), 6, color='steelblue', alpha=0.3) ax = plt.gca() ax.add_artist(circle) #scan points plt.scatter(x, y, color='steelblue', alpha=0.5) #label range plt.plot([0, 6], [0, 6 * np.tan(np.pi / 6)], color="r") plt.plot([0, -6], [0, 6 * np.tan(np.pi / 6)], color="r") wedge = Wedge((0, 0), 6, 30, 150, color='indianred', alpha=0.5) ax.add_patch(wedge) #label points plt.scatter(x_label, y_label, color='r', alpha=0.9) plt.xlim((-6, 6)) plt.ylim((-6, 6)) # plt.scatter(x,y, color='b',alpha=0.3) # plt.show() figname = str(re.findall("\d+", txtname)[0]) + ".png" print figname plt.savefig(figname) plt.close(i)
N = 3 x = np.random.rand(N) y = np.random.rand(N) radii = 0.1 * np.random.rand(N) patches = [] for x1, y1, r in zip(x, y, radii): circle = Circle((x1, y1), r) patches.append(circle) x = np.random.rand(N) y = np.random.rand(N) radii = 0.1 * np.random.rand(N) theta1 = 360.0 * np.random.rand(N) theta2 = 360.0 * np.random.rand(N) for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2): wedge = Wedge((x1, y1), r, t1, t2) patches.append(wedge) # Some limiting conditions on Wedge patches += [ Wedge((.3, .7), .1, 0, 360), # Full circle Wedge((.7, .8), .2, 0, 360, width=0.05), # Full ring Wedge((.8, .3), .2, 0, 45), # Full sector Wedge((.8, .3), .2, 45, 90, width=0.10), # Ring sector ] for i in range(N): polygon = Polygon(np.random.rand(N, 2), True) patches.append(polygon) colors = 100 * np.random.rand(len(patches))
def plot_polar_bar_plots_together(radial_bins, metric="MAE", addTitle=None, returnFig=False): assert type(metric) == str and metric in [ "MAE", "STD", "RMSE" ], "metric must be either 'MAE' (default), 'RMSE' or 'STD'." if metric == "MAE": title = "MAE\n vs.\n Joint Angle" xLabel = "MAE (in deg.)" maxValue = np.log10(radial_bins["maxMAE"]) + 2 elif metric == 'STD': title = "Error Std Dev\n vs.\n Joint Angle" xLabel = "Error Std Dev (in deg.)" maxValue = np.log10(radial_bins["maxSTD"]) + 2 elif metric == 'RMSE': title = "RMSE\n vs.\n Joint Angle" xLabel = "Log RMSE (in deg.)" maxValue = np.log10(radial_bins["maxRMSE"]) + 2 offset = 2 # assert maxValue<3.3, "Bounds not configured for values this large. Please check values again and determine if bounds need to be changed." basePath = path.dirname(__file__) filePath = path.abspath( path.join(basePath, "..", "SupplementaryFigures", "Schematic_1DOF2DOA_system.png")) im = Image.open(filePath) height = im.size[1] width = im.size[0] aspectRatio = width / height fig = plt.figure(figsize=(10, 8)) if addTitle is not None: assert type(addTitle) == str, "title must be a string." plt.title(addTitle, fontsize=16, y=-0.35) newHeight = int(np.ceil(0.15 * fig.bbox.ymax) + 10) size = int(newHeight * aspectRatio), newHeight im.thumbnail(size, Image.ANTIALIAS) fig.figimage(im, fig.bbox.xmax / 2 - im.size[0] / 2.2, 0.95 * im.size[1], zorder=10) ax = plt.gca() slices = radial_bins['bins'] thetaRays = np.arange(0, np.pi + 1e-3, np.pi / slices) sectorWidth = np.pi / slices / 5 thetaRays_SplitInFourths = [] for j in range(len(thetaRays) - 1): midAngle = (thetaRays[j + 1] + thetaRays[j]) / 2 thetaRays_SplitInFourths.append([(midAngle + i * sectorWidth) for i in [-2, -1, 0, 1]]) thetaRays_SplitInFourths = np.concatenate(thetaRays_SplitInFourths) groups = ["all", "bio", "kinapprox", "allmotor"] for j in range(len(thetaRays) - 1): bin_name = ('{:0.1f}'.format(180 * thetaRays[j] / np.pi) + " to " + '{:0.1f}'.format(180 * thetaRays[j + 1] / np.pi)) if j % 2 == 0: ax.add_patch( Wedge((0, 0), 3.3, (180 / np.pi) * thetaRays[j], (180 / np.pi) * thetaRays[j + 1], color="0.85")) for i in range(len(groups)): ax.add_patch( Wedge((0, 0), np.log10(radial_bins[groups[i]][bin_name][metric]) + 2, (180 / np.pi) * thetaRays_SplitInFourths[4 * j + i], (180 / np.pi) * (thetaRays_SplitInFourths[4 * j + i] + sectorWidth), color=colors[i], alpha=0.65)) ax.set_aspect('equal') ax.set_ylim([0, 3.3]) ax.set_xlim([-3.3, 3.3]) xticks = np.arange(0, 3 + 1e-3, 1) xticks = np.concatenate( [-np.array(list(reversed(xticks[1:]))), xticks[1:]]) ax.set_xticks(xticks) ax.set_xticklabels([ r"$10^{1}$", r"$10^{0}$", r"$10^{-1}$", r"$10^{-1}$", r"$10^{0}$", r"$10^{1}$" ]) ax.add_patch(Wedge((0, 0), 1, 0, 360, color='w')) xticksMinor = np.concatenate( [np.linspace(10**(i), 10**(i + 1), 10)[1:-1] for i in range(-1, 1)]) xticksMinor = np.concatenate( [-np.array(list(reversed(xticksMinor))), xticksMinor]) xticksMinor = [np.sign(el) * (np.log10(abs(el)) + 2) for el in xticksMinor] ax.set_xticks(xticksMinor, minor=True) yticks = list(np.arange(0, 3 + 1e-3, 1)) ax.set_yticks(yticks[1:]) ax.set_yticklabels(["" for tick in ax.get_yticks()]) yticksMinor = np.concatenate( [np.linspace(10**(i), 10**(i + 1), 10)[1:-1] for i in range(-1, 1)]) yticksMinor = [np.sign(el) * (np.log10(abs(el)) + 2) for el in yticksMinor] ax.set_yticks(yticksMinor, minor=True) radii = list(ax.get_yticks()) theta = np.linspace(0, np.pi, 201) for radius in radii: ax.plot([radius * np.cos(el) for el in theta], [radius * np.sin(el) for el in theta], "k", lw=0.5) ax.plot([1, 3.3], [0, 0], 'k', linewidth=1.5) # double lw because of ylim ax.plot([-3.3, -1], [0, 0], 'k', linewidth=1.5) # double lw because of ylim ax.plot([0, 0], [1, 3.3], 'k', linewidth=0.5) props = dict(boxstyle='round', facecolor='w', edgecolor='0.70') ax.text(-0.9 * 3, 3, title, horizontalalignment='center', verticalalignment='center', fontsize=16, bbox=props) ax.text(2, -0.35, xLabel, horizontalalignment='center', verticalalignment='center', fontsize=12) ax.spines['bottom'].set_position('zero') ax.spines['left'].set_position('zero') ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) if returnFig == True: return (fig)
def plot_station(self, data): """Plot values on a map in a station plot like manner the positions are a list of 1-9 values, where top row is 1,2,3 and then the middle row is 4,5,6 and bottom row is 7,8,9 Args: data (list): list of dicts with station data to plot """ (x0, x1) = self.ax.set_xlim() # size to use for circles circlesz = (x1 - x0) / 180. # (y0, y1) = self.ax.set_ylim() offsets = {1: [-4, 4, 'right', 'bottom'], 2: [0, 4, 'center', 'bottom'], 3: [4, 4, 'left', 'bottom'], 4: [-4, 0, 'right', 'center'], 5: [0, 0, 'center', 'center'], 6: [4, 0, 'left', 'center'], 7: [-4, -4, 'right', 'top'], 8: [0, -4, 'center', 'top'], 9: [4, -4, 'left', 'top']} mask = np.zeros(self.fig.canvas.get_width_height(), bool) for stdata in data: (x, y) = self.ax.projection.transform_point(stdata['lon'], stdata['lat'], ccrs.Geodetic()) (imgx, imgy) = self.ax.transData.transform([x, y]) imgx = int(imgx) imgy = int(imgy) # Check to see if this overlaps _cnt = np.sum(np.where(mask[imgx-15:imgx+15, imgy-15:imgy+15], 1, 0)) if _cnt > 5: continue mask[imgx-15:imgx+15, imgy-15:imgy+15] = True # Plot bars if stdata.get('sknt', 0) > 1: (u, v) = meteorology.uv(speed(stdata.get('sknt', 0), 'KT'), direction(stdata.get('drct', 0), 'DEG')) if u is not None and v is not None: self.ax.barbs(x, y, u.value('KT'), v.value('KT'), zorder=1) # Sky Coverage skycoverage = stdata.get('coverage') if (skycoverage is not None and skycoverage >= 0 and skycoverage <= 100): w = Wedge((x, y), circlesz, 0, 360, ec='k', fc='white', zorder=2) self.ax.add_artist(w) w = Wedge((x, y), circlesz, 0, 360. * skycoverage / 100., ec='k', fc='k', zorder=3) self.ax.add_artist(w) # Temperature val = stdata.get('tmpf') if val is not None: (offx, offy, ha, va) = offsets[1] self.ax.annotate("%.0f" % (val, ), xy=(x, y), ha=ha, va=va, xytext=(offx, offy), color='r', textcoords="offset points", clip_on=True) # Dew Point val = stdata.get('dwpf') if val is not None: (offx, offy, ha, va) = offsets[7] self.ax.annotate("%.0f" % (val, ), xy=(x, y), ha=ha, va=va, xytext=(offx, offy), color='b', textcoords="offset points", clip_on=True) # Plot identifier val = stdata.get('id') if val is not None: (offx, offy, ha, va) = offsets[6] self.ax.annotate("%s" % (val, ), xy=(x, y), ha=ha, va=va, xytext=(offx, offy), color='tan', textcoords="offset points", zorder=1, clip_on=True, fontsize=8)
def graph(filename, stx, sty, sta, enx, eny, op1x, op1y, op2x, op2y, robot_2nd_x, robot_2nd_y): cmd = "./main %d %d %d %d %d %d %d %d %d %d %d"%(stx, sty, sta, enx, eny, op1x, op1y, op2x, op2y, robot_2nd_x, robot_2nd_y) o,i = popen2.popen2(cmd) i.close() s = o.read(100000000) o.close() open(filename + ".txt", "w").write(s) if len(s) == 100000000: gloupix() fig = plt.figure() ax = fig.add_subplot(111) # total area limits x,y = build_poly([(0,0), (3000,0), (3000,2000), (0,2000)]) ax.plot(x, y, 'k-') # play area limits clerance = 230 purple = 100 red = 0 x,y = build_poly([(400+clerance-10+purple,clerance), (3000-400-clerance+10-red,clerance),(3000-400-clerance+10-red,2000-44-clerance), (400+clerance-10+purple,2000-44-clerance)]) #x,y = build_poly([(clerance,clerance), (3000-clerance,clerance),(3000-clerance,2000-44-clerance), (clerance,2000-44-clerance)]) #x,y = build_poly([(240,240), (3000-240,240), (3000-240,2000-240-44), (240,2000-240-44)]) ax.plot(x, y, 'c--') # sea sea = [ Rectangle((0,0), 3000, 2000) ] # black lines lines = [ Rectangle((500,450), 150, 20) ] lines += [ Rectangle((3000-500,450), -150, 20) ] lines += [ Rectangle((500+150-20,450+20), 20, 2000-(450+20)) ] lines += [ Rectangle((3000-(500+150-20),450+20), -20, 2000-(450+20)) ] # bottles red_bottles = draw_bottle(640, 2000) red_bottles += draw_bottle(3000-640-477, 2000) purple_bottles = draw_bottle(640+477, 2000) purple_bottles += draw_bottle(3000-640, 2000) # isles isles = [Circle((1100, 1000), 200)] isles += [Circle((1100+800, 1000), 200)] isles += [Circle((1500, 1000), 150/2)] isles += [Wedge((1500, 0), 300, 0, 180)] # isles patch isles_patch = [Wedge((1500, 1000-750), 550, 45, 135)] isles_patch += [Wedge((1500, 1000+750), 550, 180+45, 180+135)] # beaches beaches = [Circle((1100, 1000), 300)] beaches += [Circle((1100+800, 1000), 300)] beaches += [Wedge((1500, 0), 400, 0, 180)] beaches_patch = [Rectangle((1100, 1000-264.7), 800, 264.7*2)] # ships ships = [ Polygon([(0,500), (400,500), (350,2000), (0,2000)]) ] ships += [ Polygon([(3000-400,500), (3000,500), (3000,2000), (3000-350, 2000)]) ] # barrier barriers = [ Rectangle((0, 500), 400, 18, ls = 'solid') ] barriers += [ Rectangle((3000, 500), -400, 18, ls = 'solid') ] # holds holds = [ Rectangle((0, 2000), 340, -610, ls='solid') ] holds += [ Rectangle((3000, 2000), -340, -610,ls='solid') ] # totems totems = [ Rectangle((1100-125, 1000-125), 250, 250) ] totems += [ Rectangle((1100+800-125, 1000-125), 250, 250) ] # start areas (captain bedroom) start_area_red = [ Rectangle((0, 0), 500, 500) ] start_area_purple = [ Rectangle((2500, 0), 500, 500) ] poly = None poly_wait_pts = 0 start = None path = None patches = [] for l in s.split("\n"): m = re.match("robot at: (-?\d+) (-?\d+) (-?\d+)", l) if m: x,y,a = (int(m.groups()[0]), int(m.groups()[1]), int(m.groups()[2])) path = [ (x,y) ] a_rad = (a * math.pi / 180.) dx = 150 * math.cos(a_rad) dy = 150 * math.sin(a_rad) patches += [ Circle((x, y), 50) ] patches += [ Arrow(x, y, dx, dy, 50) ] m = re.match("oa_start_end_points\(\) \((-?\d+),(-?\d+)\) \((-?\d+),(-?\d+)\)", l) if m: dst_x,dst_y = (int(m.groups()[2]), int(m.groups()[3])) patches += [ Circle((dst_x, dst_y), 50) ] m = re.match("oa_new_poly\(size=(-?\d+)\)", l) if m: poly_wait_pts = int(m.groups()[0]) poly = [] m = re.match("opponent 1 at: (-?\d+) (-?\d+)", l) if m: poly_wait_pts = 4 poly = [] m = re.match("opponent 2 at: (-?\d+) (-?\d+)", l) if m: poly_wait_pts = 4 poly = [] m = re.match("robot 2nd at: (-?\d+) (-?\d+)", l) if m: poly_wait_pts = 4 poly = [] m = re.match("oa_poly_set_point\(\) \((-?\d+),(-?\d+)\)", l) if m: poly.append((int(m.groups()[0]), int(m.groups()[1]))) poly_wait_pts -= 1 if poly_wait_pts == 0: x,y = build_poly(poly) ax.plot(x, y, 'r-') m = re.match("GOTO (-?\d+),(-?\d+)", l) if m: path.append((int(m.groups()[0]), int(m.groups()[1]))) m = re.match("With avoidance (-?\d+): x=(-?\d+) y=(-?\d+)", l) if m: path.append((int(m.groups()[1]), int(m.groups()[2]))) m = re.match("nb_rays = (-?\d+)", l) if m: print((int(m.groups()[0]))) p = PatchCollection(sea, cmap=matplotlib.cm.jet, alpha=1, color='lightblue') ax.add_collection(p) p = PatchCollection(ships, cmap=matplotlib.cm.jet, alpha=1, color='brown') ax.add_collection(p) p = PatchCollection(holds, cmap=matplotlib.cm.jet, alpha=0.5, color='grey') ax.add_collection(p) p = PatchCollection(lines, cmap=matplotlib.cm.jet, alpha=1, color='black') ax.add_collection(p) p = PatchCollection(beaches_patch, cmap=matplotlib.cm.jet, alpha=1, color='yellow') ax.add_collection(p) p = PatchCollection(isles_patch, cmap=matplotlib.cm.jet, alpha=1, color='lightblue') ax.add_collection(p) p = PatchCollection(beaches, cmap=matplotlib.cm.jet, alpha=1, color='yellow') ax.add_collection(p) p = PatchCollection(isles, cmap=matplotlib.cm.jet, alpha=1, color='green') ax.add_collection(p) p = PatchCollection(totems, cmap=matplotlib.cm.jet, alpha=1, color='brown') ax.add_collection(p) p = PatchCollection(start_area_purple, cmap=matplotlib.cm.jet, alpha=1, color='purple') ax.add_collection(p) p = PatchCollection(start_area_red, cmap=matplotlib.cm.jet, alpha=1, color='red') ax.add_collection(p) p = PatchCollection(red_bottles, cmap=matplotlib.cm.jet, alpha=1, color='red') ax.add_collection(p) p = PatchCollection(purple_bottles, cmap=matplotlib.cm.jet, alpha=1, color='purple') ax.add_collection(p) p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4) ax.add_collection(p) x,y = build_path(path) ax.plot(x, y, 'bo-') ax.grid() ax.set_xlim(-100, 3100) ax.set_ylim(-100, 2500) #ax.set_title('spline paths') #plt.show() fig.savefig(filename)
def plot(): from matplotlib.patches import Circle, Ellipse, Polygon, Rectangle, Wedge from matplotlib.collections import PatchCollection from matplotlib import pyplot as plt import numpy as np import matplotlib as mpl np.random.seed(123) fig = plt.figure() ax = fig.add_subplot(111) N = 3 x = np.random.rand(N) y = np.random.rand(N) radii = 0.1 * np.random.rand(N) patches = [] for x1, y1, r in zip(x, y, radii): circle = Circle((x1, y1), r) patches.append(circle) rect = Rectangle(xy=[0.0, 0.25], width=1.0, height=0.5, angle=-45.0) patches.append(rect) x = np.random.rand(N) y = np.random.rand(N) radii = 0.1 * np.random.rand(N) theta1 = 360.0 * np.random.rand(N) theta2 = 360.0 * np.random.rand(N) for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2): wedge = Wedge((x1, y1), r, t1, t2) patches.append(wedge) # Some limiting conditions on Wedge patches += [ Wedge((0.3, 0.7), 0.1, 0, 360), # Full circle Wedge((0.7, 0.8), 0.2, 0, 360, width=0.05), # Full ring Wedge((0.8, 0.3), 0.2, 0, 45), # Full sector Wedge((0.8, 0.3), 0.2, 45, 90, width=0.10), # Ring sector ] for _ in range(N): polygon = Polygon(np.random.rand(N, 2), True) patches.append(polygon) colors = 100 * np.random.rand(len(patches)) p = PatchCollection(patches, cmap=mpl.cm.jet, alpha=0.4) p.set_array(np.array(colors)) ax.add_collection(p) ellipse = Ellipse(xy=[1.0, 0.5], width=1.0, height=0.5, angle=45.0, alpha=0.4) ax.add_patch(ellipse) circle = Circle(xy=[0.0, 1.0], radius=0.5, color="r", alpha=0.4) ax.add_patch(circle) plt.colorbar(p) return fig