def save_bar_chart(data, ylabel, xlabel, title, figname, ylimits=None, under_median=None, over_median=None): """ Saves a standard bar chart with the specified attributes and file name """ fig = plt.figure() ax = fig.add_subplot(111) # our standard type for this project rects = ax.bar(np.arange(len(data)), data, width=1, color='b') #our standard settings ax.set_ylabel(ylabel) ax.set_xlabel(xlabel) ax.set_title(title) if ylimits: plt.ylim(ylimits) plt.subplots_adjust(top=0.86) #move the title up a bit if under_median: ax.add_artist( AnchoredText("Underperformers:\nmedian:%s%%" % (under_median.round(2)), loc=2, prop=dict(size=12))) if over_median: ax.add_artist( AnchoredText("Outperformers:\nmedian:%s%%" % (over_median.round(2)), loc=4, prop=dict(size=12))) print 'Saving figure', figname plt.savefig(figname)
def plot_fig(filename, fig_title=''): fig = figure(1) grid = Grid(fig, 111, nrows_ncols=(3, 1), axes_pad=0.15) #subplot(311) grid[0].set_title(fig_title) grid[0].plot(z, c_den[0], lw=2.0, c='b') grid[0].plot(z, c_den[1], lw=2.0, c='r') grid[0].plot(z, c_den[2], lw=2.0, c='g') grid[0].axvline(0, linestyle='--', c='k') grid[0].axvline(d[1], linestyle='--', c='k') grid[0].set_ylabel('Comp.') grid[0].legend(('Substrate', 'Fe layer', 'Ambient')) #subplot(312) grid[1].plot(z, m_den[1], lw=2.0, c='r') grid[1].axvline(0, linestyle='--', c='k') grid[1].axvline(d[1], linestyle='--', c='k') grid[1].axvline(0 + ddm[0], linestyle=':', c='k') grid[1].axvline(d[1] + ddm[1], linestyle=':', c='k') #grid[1].annotate('Sub.dd_m = %.1f'%ddm[0], xy=(ddm[0], mag_dens[1]), xycoords = 'data', # xytext = (-50, 0), textcoords = 'offset points', # arrowprops=dict(arrowstyle="->", connectionstyle = 'arc3')) #grid[1].annotate('Fe.dd_m = %.1f'%ddm[1], xy=(d[1]+ddm[1], mag_dens[1]), xycoords = 'data', # xytext = (50, 0), textcoords = 'offset points', # arrowprops=dict(arrowstyle="<-", connectionstyle = 'arc3')) at = AnchoredText( "dd_ml = %.1f" % (ddm[0]), prop=dict(size=10), frameon=True, loc=6, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") grid[1].add_artist(at) at = AnchoredText( "dd_mu = %.1f" % (ddm[1]), prop=dict(size=10), frameon=True, loc=7, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") grid[1].add_artist(at) grid[1].set_ylabel('Mag. mom.\n per res. atom.') grid[1].set_ylim(0, 3.1) #subplot(313) grid[2].plot(z, m_den[1] * c_den[1], 'r', z, 2.25 * c_den[1], 'b', lw=2.0) grid[2].axvline(0, linestyle='--', c='k') grid[2].axvline(d[1], linestyle='--', c='k') grid[2].axvline(0 + ddm[0], linestyle=':', c='k') grid[2].axvline(d[1] + ddm[1], linestyle=':', c='k') grid[2].set_ylabel('Tot. Mag mom.') grid[2].legend(('Profile', 'Bulk Fe')) grid[2].set_xlabel('Depth [AA]') savefig(filename) clf()
def onpick(event): global at #remove the current text box when click event is triggered at.remove() #store index of clicked town circle ind = event.ind #store the data about the town as separate strings place = np.take(name, ind)[0] pop = np.take(population, ind)[0] lon = np.take(longitude, ind)[0] lat = np.take(latitude, ind)[0] #if circle is red then it is a city if np.take(colour, ind)[0] == 'r': size = 'City' #otherwise it is a town else: size = 'Town' #create string to be in text box textdata = size + ' - ' + place + ', Population: ' + pop + ', Latitude: ' + lat + ', Longitude: ' + lon #create new anchored text box and add to axes at = AnchoredText(textdata, prop=dict(size=10), frameon=True, loc=2) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) #update the plot with the new text box plt.draw()
def plot_axe(self, ax, current_values, average_values): """give me a ax and two list datas, i can plot two list on the axe you give Parameters ---------- ax : plt.figure.axe The axe you are going to draw. current_values : float list current new data list. average_values : Tfloat list current new average data list. Returns ------- None Examples -------- .. code:: python # Example usage of myfunction self.plot_axe(ax0_cur1_avr2[0], ax0_cur1_avr2[1], ax0_cur1_avr2[2]) """ ax.cla() ax.plot(current_values, "r--o", linewidth=2.0, alpha=1) ax.plot(average_values, "g-o" , linewidth=2.0, alpha=0.4) at = AnchoredText("cur:%.2f\navr:%.2f"%(current_values[-1], average_values[-1]), prop=dict(size=8), frameon=True, loc=2, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) ax.grid(True)
def _fit_model(self, masked_data, components, label): em = myEM(components) em.fit(masked_data) gamma_gauss_pp = em.posteriors(masked_data) bic = em.BIC(masked_data) fig = plt.figure() ax = fig.add_subplot(111) plt.hist(masked_data, bins=50, normed=True) xRange = np.arange(math.floor(min(masked_data)), math.ceil(max(masked_data)), 0.1) pdf_sum = np.zeros(xRange.shape) for i, component in enumerate(em.components): pdf = component.pdf(xRange) * em.mix[i] plt.plot(xRange, pdf) pdf_sum += pdf at = AnchoredText( "BIC = %f" % (bic), loc=1, prop=dict(size=8), frameon=True, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) plt.plot(xRange, pdf_sum) plt.xlabel("T values") plt.savefig("histogram%s.pdf" % label) return gamma_gauss_pp, bic, ax
def hist(tres): """ Histogram Shows the S/N ratio of the highest significance peak in the periodogram. """ assert len(unique(tres.Pblock))==1,'Periods must be the same' assert len(unique(tres.KIC))==1,'Must compare the same star' KIC = unique(tres.KIC)[0] dfL = unique(tres.df) fig,axL = subplots(nrows=len(dfL),sharex=True,figsize=( 5, 12)) for df,ax in zip(dfL,axL): tg = tres.where( (tres.df == df) & tres.bg) tb = tres.where( (tres.df == df) & ~tres.bg) ax.hist(tg.os2n,color='green',bins=arange(100), label='%d' % len(tg.data)) ax.hist(tb.os2n,color='red',bins=arange(100), label='%d' % len(tb.data)) ax.legend() tprop = dict(size=10,name='monospace') at = AnchoredText(r"%i ppm" % df,prop=tprop, frameon=True,loc=3) ax.add_artist(at) ax.yaxis.set_major_locator(MaxNLocator(nbins=5,prune='upper')) xlabel('s2n')
def citation(text, figure=None, axes=None): """ Add a text citation to a plot. Places an anchored text citation in the bottom right hand corner of the plot. Args: * text: Citation text to be plotted. Kwargs: * figure: Target :class:`matplotlib.figure.Figure` instance. Defaults to the current figure if none provided. * axes: the :class:`matplotlib.axes.Axes` to use for drawing. Defaults to the current axes if none provided. """ if text is not None and len(text): if figure is None and not axes: figure = plt.gcf() anchor = AnchoredText(text, prop=dict(size=6), frameon=True, loc=4) anchor.patch.set_boxstyle('round, pad=0, rounding_size=0.2') axes = axes if axes else figure.gca() axes.add_artist(anchor)
def textonly(ax, txt, fontsize=14, loc=2, *args, **kwargs): at = AnchoredText(txt, prop=dict(size=fontsize), frameon=True, loc=loc) at.patch.set_boxstyle("round, pad=0., rounding_size=0.2") ax.add_artist(at) return at
def plot(title, xlabel, ylabel, filename, width, height, data, info): global mc pl = Plot(title, xlabel, ylabel, filename, width, height, 1) if len(data) > 0: for k, v in data.iteritems(): diff = (float(v["y"]['tps']) - float(v["x"]['tps'])) / float( v["y"]['tps']) * 100. acolor = ['g', 'r'][diff < 0] pl.plot(v["x"]['tps'], v["y"]['tps'], acolor, MARKERS[0], "") if abs(diff) > 5.: atxt = "%s %d %s (%.2f%%)" % (k[2], k[3], ["node", "nodes" ][k[3] > 1], diff) pl.ax.annotate( atxt, xy=(v["x"]['tps'], v["y"]['tps']), xycoords='data', xytext=(10 * [1, -1][diff > 0], -5), textcoords='offset points', ha=["left", "right"][diff > 0], size=10, color=acolor) #, arrowprops=dict(arrowstyle="->")) if len(info) > 1: _at = AnchoredText("\n".join(info), loc=2, prop=dict(size=10)) pl.ax.add_artist(_at) pl.close()
def times_insets(rectkw={}): _times = times.copy() rectkw = dict(color='none', ec='blue') axL = gcf().get_axes() inset(axL[0], axL[1], (2500, 0), 1500, 0.6, label='b', rectkw=rectkw) at = AnchoredText('a', frameon=True, loc=2, prop=figlabelprop) axL[0].add_artist(at) xy = _times.iloc[:6].mean() xy = xy.tc, 0 #import pdb;pdb.set_trace() ephem = 'linear' if ephem == 'linear': w = 140 h = 0.08 xy = (mean(_times.query('inst=="K2"').tc), -0.01) inset(axL[1], axL[2], xy, w, h, label='c', rectkw=rectkw) # transit temp = _times[_times.inst.str.contains('FLWO|TRAPPIST|MuSCAT')] xy = (mean(temp.tc), -0.00) inset(axL[1], axL[3], xy, w, h, label='e', loc='below', rectkw=rectkw) temp = _times[_times.inst.str.contains('Spitzer')] xy = (mean(temp.tc), +0.03) inset(axL[1], axL[4], xy, w, h, label='d', rectkw=rectkw) # transit
def fitselect(xmin, xmax): """ This function will fit a line to a manually selected region of the work-current plot. The fit will be added to the plot for visualization and the slope will be returned in pA/fJ. """ indmin, indmax = np.searchsorted(self.approach[x], (xmin, xmax)) indmax = min(len(self.approach[x]) - 1, indmax) subx = self.approach[x][indmin:indmax] suby = self.approach[y][indmin:indmax] try: poptLin = curve_fit(linFit, subx, suby)[0] except RuntimeError: print("Error - curve fit failed") from mpl_toolkits.axes_grid.anchored_artists import AnchoredText at = AnchoredText( "Sensitivity: " + str(round(poptLin[0], 3)) + " (pA/fJ)", prop=dict(size=8), frameon=True, loc=2, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) fitY = poptLin[0] * subx + poptLin[1] ax.plot(subx, fitY, '--', color='red') ax.axvspan(self.approach[x][indmin], self.approach[x][indmax], color='grey', alpha=0.25) slopes.append(round(poptLin[0], 3)) fig.canvas.draw()
def add_anchored(*args,**kwargs): """ Parameters ---------- s : string Text. loc : str Location code. pad : float, optional Pad between the text and the frame as fraction of the font size. borderpad : float, optional Pad between the frame and the axes (or *bbox_to_anchor*). prop : `matplotlib.font_manager.FontProperties` Font properties. """ bbox = {} if kwargs.has_key('bbox'): bbox = kwargs.pop('bbox') at = AnchoredText(*args, **kwargs) if len(bbox.keys())>0: pl.setp(at.patch,**bbox) ax = pl.gca() ax.add_artist(at)
def inset(ax1, ax2, center, width, height, label=None, loc='above', rectkw={}): """Draw an inset Draws an rectangle on ax1 with a given center, width and height. Sets the limits of ax2 to correspond to ax1 rectangle Args: ax1: big axis ax2: detail axis """ xy = (center[0] - 0.5 * width, center[1] - 0.5 * height) sca(ax1) p = matplotlib.patches.Rectangle(xy, width, height, **rectkw) ax1.add_artist(p) sca(ax2) xlim(center[0] - 0.5 * width, center[0] + 0.5 * width) ylim(center[1] - 0.5 * height, center[1] + 0.5 * height) if label is not None: if loc == "above": x = center[0] y = center[1] + 0.5 * height va = 'bottom' elif loc == "below": x = center[0] y = center[1] - 0.5 * height va = 'top' sca(ax1) text(x, y, label, fontweight='bold', va=va) sca(ax2) at = AnchoredText(label, frameon=True, loc=2, prop=figlabelprop) ax2.add_artist(at)
def addAnnotationToPlot(plot, text, loc=1, size=6.): from mpl_toolkits.axes_grid. anchored_artists import AnchoredText at = AnchoredText(text, prop=dict(size=size), frameon=True, loc=loc, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") plot.add_artist(at)
def add_custom_legend(ax, txt, fontsize=12, loc=1, *args, **kwargs): at = AnchoredText(txt, prop=dict(size=fontsize), frameon=True, loc=loc) at.patch.set_boxstyle("round,pad=0.2,rounding_size=0.2") ax.add_artist(at) return at
def _imshow(pl, what, label, cmap): pl.grid() pl.imshow(what, cmap=cmap) pl.tick_params(axis='both', which='major', labelsize=10) at = AnchoredText( label, loc=2) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") pl.add_artist(at)
def AddAnchored(*args,**kwargs): # Hack to get rid of warnings for k in 'ha va'.split(): if k in kwargs['prop']: kwargs['prop'].pop(k) at = AnchoredText(*args,**kwargs) plt.gca().add_artist(at)
def add_anchored(*args, **kwargs): ax = gca() letter_bbox_props = dict(boxstyle="round,pad=0.,rounding_size=0.2", fc='w', alpha=0.7, ec='none') at = AnchoredText(*args, **kwargs) ax.add_artist(at) setp(at.patch, **letter_bbox_props)
def set_name(self, name, frameon=True): self.name = name if name: at = AnchoredText( self.name, loc=2, frameon=frameon, prop=dict(size=12) ) self.add_artist(at) return at
def check_trace_order(flat_deriv, trace_dict, fig, rowcol=(1, 3), rect=111, title_fontsize=None): from mpl_toolkits.axes_grid1 import ImageGrid #from axes_grid import ImageGrid #d = trace_products["flat_deriv"] # from storage_descriptions import (FLAT_DERIV_DESC, # FLATCENTROIDS_JSON_DESC) # d = trace_products[FLAT_DERIV_DESC].data # trace_dict = trace_products[FLATCENTROIDS_JSON_DESC] grid = ImageGrid(fig, rect, rowcol, share_all=True) ax = grid[0] im = ax.imshow(flat_deriv, origin="lower", interpolation="none", cmap="RdBu") im.set_clim(-0.05, 0.05) ax = grid[1] for l in trace_dict["bottom_centroids"]: ax.plot(l[0], l[1], "r-") for l in trace_dict["up_centroids"]: ax.plot(l[0], l[1], "b-") ax = grid[2] im = ax.imshow(flat_deriv, origin="lower", interpolation="none", cmap="RdBu") im.set_clim(-0.05, 0.05) for l in trace_dict["bottom_centroids"]: ax.plot(l[0], l[1], "r-") for l in trace_dict["up_centroids"]: ax.plot(l[0], l[1], "b-") ax.set_xlim(0, 2048) ax.set_ylim(0, 2048) if title_fontsize is None: return for ax, title in zip(grid, ["Derivative Image", "Traced Boundary", "Together"]): at = AnchoredText( title, prop=dict(size=title_fontsize), frameon=True, loc=2, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at)
def draw_text(ax): from mpl_toolkits.axes_grid.anchored_artists import AnchoredText at = AnchoredText( "Figure 1a", loc=2, prop=dict(size=8), frameon=True, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) at2 = AnchoredText("Figure 1(b)", loc=3, prop=dict(size=8), frameon=True, bbox_to_anchor=(0., 1.), bbox_transform=ax.transAxes) at2.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at2)
def unfolded_artefact_plot(heart_array, diagnostic_data, save_to, log): """ Plot heart_array at max value in diagnostic data. """ # Might be a bit naive assuming that the sites are at the max point of the diagnostic data... # There is probably a better way of going about this... x,y,z = np.unravel_index(np.argmax(diagnostic_data), np.shape(diagnostic_data)) artefact_site = [x,y,z] fig, ax = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, figsize=[10,10]) fig.suptitle("Unfolded SPECT scan at simulated artefact site, "+str(artefact_site), size=16) fig.subplots_adjust(top=0.92) ax[0,1].axis("off") ax[0,0].imshow(heart_array[artefact_site[0]], cmap="gray") ax[0,0].axhline(y=artefact_site[1], linewidth=2, color='red') ax[0,0].axvline(x=artefact_site[2], linewidth=2, color='red') at = AnchoredText("x = "+str(artefact_site[0]), prop=dict(size=8), frameon=True, loc=4) at.patch.set_boxstyle("square") ax[0,0].add_artist(at) ax[1,0].imshow(heart_array[:,artefact_site[1]], cmap="gray") ax[1,0].axhline(y=artefact_site[0], linewidth=2, color='red') ax[1,0].axvline(x=artefact_site[2], linewidth=2, color='red') at = AnchoredText("y = "+str(artefact_site[1]), prop=dict(size=8), frameon=True, loc=4) at.patch.set_boxstyle("square") ax[1,0].add_artist(at) ax[1,1].imshow(heart_array[:,:,artefact_site[2]], cmap="gray") ax[1,1].axhline(y=artefact_site[0], linewidth=2, color='red') ax[1,1].axvline(x=artefact_site[1], linewidth=2, color='red') at = AnchoredText("z = "+str(artefact_site[2]), prop=dict(size=8), frameon=True, loc=4) at.patch.set_boxstyle("square") ax[1,1].add_artist(at) fig.subplots_adjust(hspace=0, wspace=0) if log: plt.savefig(save_to) else: plt.show()
def refreshPlotText(self): at = AnchoredText( self.outText, prop=dict(size=12), frameon=True, loc=1, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") self.axes.add_artist(at) self.canvas.draw()
def plot_all_antenas_selection_per_pointing(fileopened, pol, antennas, chan_range, targets): fig = plt.figure() if pol == 'H': fig.suptitle( 'All antennas mean horizontal auto-correlation spectra per pointing', size='small', fontweight='bold') elif pol == 'V': fig.suptitle( 'All antennas mean vertical auto-correlation spectra per pointing', size='small', fontweight='bold') grid = Grid(fig, 111, nrows_ncols=(4, 5), axes_pad=0.0, share_all=True) all_text = [] for index, targ in enumerate(targets): fileopened.select(corrprods='auto', pol=pol, targets=targ, channels=chan_range, scans='~slew') freqs = fileopened.channel_freqs * 1.0e-6 data = np.abs(fileopened.vis[:].mean(axis=0)) ylim = (0, 1.2 * data.max()) xlim = (freqs[0], freqs[-1]) spikes = detect_spikes_orig(data) #detect spikes seen in all antennas per each pointing rfi_inall_ants = [ freqs[i] for i, elem in enumerate(spikes.all(axis=1)) if elem ] label = "Flags [MHz]:\n" text = targ + '\n' + label + '\n'.join( ['%.3f' % num for num in rfi_inall_ants]) all_text.append(text) at = AnchoredText(text, prop=dict(size=4), frameon=True, loc=2) grid[index].add_artist(at) #print targ, rfi_inall_ants for k, ant in enumerate(antennas): #detect spikes per antenna for each pointing rfi_freqs = [ freqs[i] for i, elem in enumerate(spikes[:, k]) if elem ] rfi_power = [ data[:, k][i] for i, elem in enumerate(spikes[:, k]) if elem ] grid[index].scatter(rfi_freqs, rfi_power, marker='+', color='Maroon') grid[index].plot(freqs, data) grid[index].add_artist(at) plt.setp(grid[index], xticks=[], yticks=[], ylim=ylim, xlim=xlim) return ('\n'.join(all_text), fig)
def boxplot_2box(value01T_L, value11N_L, figureName, target, pvalue): ## combine these different collections into a list value01T_Log = [log(y, 10) for y in value01T_L] value11N_Log = [log(x, 10) for x in value11N_L] data_to_plot = [value01T_Log, value11N_Log] countT = len(value01T_L) countN = len(value11N_L) x_lable1 = "T (n=" + str(countT) + ")" x_lable2 = "N (n=" + str(countN) + ")" # Create a figure instance fig = plt.figure(1, figsize=(9, 6)) # Create an axes instance ax = fig.add_subplot(111) # Create the boxplot,patch_artist: fill with color, #bp = ax.boxplot(data_to_plot,labels=[x_lable1,x_lable2], patch_artist=True,widths=(0.5,0.5)) bp = ax.boxplot(data_to_plot, labels=[x_lable1, x_lable2], widths=(0.4, 0.4)) # Labels Title = target + " Expression in Colorectal Cancer" ax.set_title(Title, fontsize=20) ax.set_ylabel('log10(FPKM-UQ)', color='black', fontsize=16) p_label = "P value=" + str(pvalue) at = AnchoredText( p_label, prop=dict(size=12), frameon=False, loc=1, ) ax.add_artist(at) # Grid lines #ax.yaxis.grid(True) #ax.axvline(linewidth=4, color="r") for i in [1, 2]: y = data_to_plot[i - 1] x = np.random.normal(i, 0.02, len(y)) plt.plot(x, y, 'r.', alpha=0.2) # Color #colors=['pink','lightblue'] #for patch,color in zip(bp['boxes'],colors): # patch.set_facecolor(color) # Save the figure plt.show() fig.savefig(figureName, bbox_inches='tight')
def fitting(request): csv_file = request.FILES['myFile'] csv_file.seek(0) reader = csv.reader(io.StringIO(csv_file.read().decode('utf-8-sig'))) fitting_results = csv_reader(reader) if fitting_results[1]: return HttpResponse(fitting_results[1]) else: output = {} output['effective_density'] = str.format( '{0:.3f}', fitting_results[0]['sigma'] / sc.micro) output['R2'] = str.format('{0:.3f}', fitting_results[0]['r2']) plt.gcf().clear() fig, ax = plt.subplots() plt.plot(fitting_results[0]['P_experiment'], fitting_results[0]['P_theory'], 'ro', label='Penetration') plt.axis('square') lim = (np.min([ax.get_xlim()[0], ax.get_ylim()[0]]), np.max([ax.get_xlim()[1], ax.get_ylim()[1]])) ax.set_xlim(lim) ax.set_ylim(lim) plt.plot([0, 1], [0, 1], 'k--', label='1:1') plt.plot([0, 0.9], [0.1, 1], 'k:', label=r'$\pm$ 0.1') plt.plot([0.1, 1], [0, 0.9], 'k:', label='_nolegend_') ax.grid(True, which='both', zorder=0) plt.xlabel('Measured penetration (-)') plt.ylabel('Predicted penetration (-)') plt.legend(loc=4) at = AnchoredText( r'$\sigma_e$ = ' + str.format('{0:.0f}', fitting_results[0]['sigma'] / sc.micro) + r' $\mathrm{\mu C/m^2}$' + '\n' + r'$\mathrm{R}^2 = $' + str.format('{0:.2f}', fitting_results[0]['r2']), prop=dict(size=8), frameon=True, loc=2, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) plt.tight_layout() buf = io.BytesIO() fig.savefig(buf, format='png') buf.seek(0) string = base64.b64encode(buf.read()) uri = 'data:image/png;base64,' + urllib.parse.quote(string) html = '<img src = "%s"/>' % uri output['figure'] = urllib.parse.quote(string) #plt.savefig(os.path.join(BASE_DIR,'static','personal','images','fit.png')) return render(request, 'personal/fitting.html', output)
def main(): cars = pd.read_csv(sys.argv[1]) cars.columns = [ 'VehicleName', 'SmallSporty', 'SportsCar', 'SUV', 'Wagon', 'Minivan', 'Pickup', 'AWD', 'RWD', 'RetailPrice', 'DealerCost', 'EngineSize(l)', 'Cyl', 'HP', 'CityMPG', 'HwyMPG', 'Weight', 'WheelBase', 'Len', 'Width' ] cars['Type'] = 0 # set the Type value based on the car cars.loc[cars.SmallSporty == 1, 'Type'] = 1 cars.loc[cars.SportsCar == 1, 'Type'] = 2 cars.loc[cars.SUV == 1, 'Type'] = 3 cars.loc[cars.Wagon == 1, 'Type'] = 4 cars.loc[cars.Minivan == 1, 'Type'] = 5 cars.loc[cars.Pickup == 1, 'Type'] = 6 # clean the data removing any '*' and converting str to ints cars = cars[cars.CityMPG != '*'] cars = cars[cars.Weight != '*'] cars.Weight = pd.to_numeric(cars.Weight, errors='coerce') # create and display the scatterplot num = 1 fig, ax = plt.subplots() for color in ['red', 'green', 'blue', 'magenta', 'cyan', 'yellow']: X = cars['HP'].where(cars['Type'] == num).dropna() Y = cars['CityMPG'].where(cars['Type'] == num).dropna() size = cars['Weight'] / 50 ax.scatter(X, Y, c=color, s=size, marker='s', edgecolors=(0, 0, 0), label=cars.columns[num]) num = num + 1 at = AnchoredText( "*Size of marker is Weight", prop=dict(size=9), frameon=True, loc=7, ) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) ax.legend() plt.xlabel("HP") plt.ylabel("City MPG") plt.title("Horse Power vs City MPG") plt.savefig(sys.argv[2])
def figure_numbering(text): artist = AnchoredText( text, prop=dict(size=12), frameon=True, loc=2, # 2: upper left pad=0.1, bbox_to_anchor=(-.1, 1.15), bbox_transform=plt.gca().transAxes) #artist.patch.set_boxstyle(fc='#FFFFFF00',ec='#FFFFFF00') artist.patch.set_fc('white') artist.patch.set_ec('white') return artist
def __init__(self, parent, trace, fig_nrows=1, fig_ncols=1, ax_pos=1): super(TracePlot, self).__init__() self.parent = parent self.fig = parent.fig self.ax = self.fig.add_subplot(fig_nrows, fig_ncols, ax_pos, visible=False) self.trace = trace # Get trace dataseries self.signal = trace.signal self.time = np.linspace(0, len(self.signal) / trace.fs, num=len(self.signal), endpoint=False) self.xmin, self.xmax = 0, self.time[-1] # Plot current data self._plot_data = self.ax.plot(self.time, self.signal, color='black', rasterized=True)[0] self.ax.callbacks.connect('xlim_changed', self.on_xlim_change) self.ax.set_xlim(self.xmin, self.xmax) # Format axes axes_formatter = FuncFormatter( lambda x, pos: clt.float_secs_2_string_date(x, trace.starttime)) self.ax.xaxis.set_major_formatter(axes_formatter) plt.setp(self.ax.get_xticklabels(), visible=False) plt.setp(self.ax.get_yticklabels(), visible=False) self.ax.grid(True, which='both') # Set event markers self.marker_select_color = 'r' self.marker_color = 'b' self.markers = {} self.update_markers() # Selection parameters self.selected = False self.selector = self.ax.axvspan(0, self.xmax, fc='LightCoral', ec='r', alpha=0.5, visible=False) #, animated=True) # Place legend at = AnchoredText(self.trace.short_name, prop=dict(size=12), frameon=True, loc=2) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") self.ax.add_artist(at)
def text_legend(ax, txt): """ This function creates a plot legend that contains text only :param ax: Current plot axis :param txt: Legend text :return: at: anchored text object """ at = AnchoredText(txt, loc='lower left', prop=dict(size=6), frameon=True, bbox_to_anchor=(-0.0, -0.45), bbox_transform=ax.transAxes) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") ax.add_artist(at) return at
def plot_state(directions_list, trim_names=True): """ Plots the facets of a run """ global midRA, midDec, fig, at, selected_direction selected_direction = None # Set up coordinate system and figure points, midRA, midDec = factor.directions.getxy(directions_list) fig = plt.figure(1, figsize=(10,9)) if hasWCSaxes: wcs = factor.directions.makeWCS(midRA, midDec) ax = WCSAxes(fig, [0.16, 0.1, 0.8, 0.8], wcs=wcs) fig.add_axes(ax) else: ax = plt.gca() field_x = min(points[0]) field_y = max(points[1]) adjust_xy = True while adjust_xy: adjust_xy = False for xy in points: dist = np.sqrt( (xy[0] - field_x)**2 + (xy[1] - field_y)**2 ) if dist < 10.0: field_x -= 1 field_y += 1 adjust_xy = True break field_ra, field_dec = factor.directions.xy2radec([field_x], [field_y], refRA=midRA, refDec=midDec) field = Direction('field', field_ra[0], field_dec[0], factor_working_dir=directions_list[0].working_dir) directions_list.append(field) ax.set_title('Overview of FACTOR run in\n{}'.format(directions_list[0].working_dir)) # Plot facets markers = [] for direction in directions_list: if direction.name != 'field': vertices = read_vertices(direction.vertices_file) RAverts = vertices[0] Decverts = vertices[1] xverts, yverts = factor.directions.radec2xy(RAverts, Decverts, refRA=midRA, refDec=midDec) xyverts = [np.array([xp, yp]) for xp, yp in zip(xverts, yverts)] mpl_poly = Polygon(np.array(xyverts), edgecolor='#a9a9a9', facecolor='#F2F2F2', clip_box=ax.bbox, picker=3.0, linewidth=2) else: xverts = [field_x] yverts = [field_y] mpl_poly = Circle((field_x, field_y), radius=5.0, edgecolor='#a9a9a9', facecolor='#F2F2F2', clip_box=ax.bbox, picker=3.0, linewidth=2) mpl_poly.facet_name = direction.name mpl_poly.completed_ops = get_completed_ops(direction) mpl_poly.started_ops = get_started_ops(direction) mpl_poly.current_op = get_current_op(direction) set_patch_color(mpl_poly, direction) ax.add_patch(mpl_poly) # Add facet names if direction.name != 'field': poly_tuple = tuple([(xp, yp) for xp, yp in zip(xverts, yverts)]) xmid = SPolygon(poly_tuple).centroid.x ymid = SPolygon(poly_tuple).centroid.y else: xmid = field_x ymid = field_y if trim_names: name = direction.name.split('_')[-1] else: name = direction.name marker = ax.text(xmid, ymid, name, color='k', clip_on=True, clip_box=ax.bbox, ha='center', va='bottom') marker.set_zorder(1001) markers.append(marker) # Add info box at = AnchoredText("Selected direction: None", prop=dict(size=12), frameon=True, loc=3) at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2") at.set_zorder(1002) ax.add_artist(at) ax.relim() ax.autoscale() ax.set_aspect('equal') if hasWCSaxes: RAAxis = ax.coords['ra'] RAAxis.set_axislabel('RA', minpad=0.75) RAAxis.set_major_formatter('hh:mm:ss') DecAxis = ax.coords['dec'] DecAxis.set_axislabel('Dec', minpad=0.75) DecAxis.set_major_formatter('dd:mm:ss') ax.coords.grid(color='black', alpha=0.5, linestyle='solid') else: plt.xlabel("RA (arb. units)") plt.ylabel("Dec (arb. units)") # Define coodinate formater to show RA and Dec under mouse pointer ax.format_coord = formatCoord # Show legend not_processed_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#F2F2F2', linewidth=2) processing_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#F2F5A9', linewidth=2) selfcal_ok_patch = plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#A9F5A9', linewidth=2) selfcal_not_ok_patch =plt.Rectangle((0, 0), 1, 1, edgecolor='#a9a9a9', facecolor='#F5A9A9', linewidth=2) l = ax.legend([not_processed_patch, processing_patch, selfcal_ok_patch, selfcal_not_ok_patch], ['Unprocessed', 'Processing', 'Completed', 'Failed']) l.set_zorder(1002) # Add check for mouse clicks and key presses fig.canvas.mpl_connect('pick_event', on_pick) fig.canvas.mpl_connect('key_press_event', on_press) # Add timer to update the plot every 60 seconds timer = fig.canvas.new_timer(interval=60000) timer.add_callback(update_plot) timer.start() # Show plot plt.show() plt.close(fig) # Clean up any temp pyrap images if not hasaplpy: if os.path.exists('/tmp/tempimage'): try: shutil.rmtree('/tmp/tempimage') except OSError: pass